Ruby

Special Processing for First and Last Items in Hash and Array with each_with_index in Ruby

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 <code>,</code> just before <code>}</code>.

Shou Arisaka
1 min read
Oct 31, 2025

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|.

Share this article

Shou Arisaka Oct 31, 2025

๐Ÿ”— Copy Links