In the Ruby programming language, this article introduces how to use each_with_index with hashes and arrays to perform special processing only for the first and last elements.
Example: Want to create JSON format from a hash. Want to remove the , just before }.
h = {:a => "hoge", :b => "fuga", :c => "foo"}
@json = '{'
h.each_with_index do |(k, v), i|
if i == 0
# Processing for the first element
end
if i == h.size - 1
# Processing for the last element
@json << %("#{k}":"#{v}")
else
@json << %("#{k}":"#{v}",)
end
end
@json << '}'
puts @json #=> {"a":"hoge","b":"fuga","c":"foo"}
This method can also be used with arrays. For arrays,
change the |(k, v), i| part to |e, i|.