 <p>You need <code>@temp = 0</code> at the beginning of each block of code.</p> <p>After executing your code with the modification</p> <pre><code>list = [{"name"=&gt;"Germany", "id"=&gt;1}, {"name"=&gt;"USA", "id"=&gt;2}, {"name"=&gt;"USA", "id"=&gt;3}, {"name"=&gt;"France", "id"=&gt;4}, {"name"=&gt;"France", "id"=&gt;5}, {"name"=&gt;"France", "id"=&gt;6}] </code></pre> <p>We can then obtain your desired result as follows.</p> <pre><code>list.group_by { |h| h["name"] }.values.flat_map do |a| a.map.with_index(1) do |h,i| base = h["name"] h.merge("name"=&gt;base +" #{i}") end end #=&gt; [{"name"=&gt;"Germany 1", "id"=&gt;1}, # {"name"=&gt;"USA 1", "id"=&gt;2}, # {"name"=&gt;"USA 2", "id"=&gt;3}, # {"name"=&gt;"France 1", "id"=&gt;4}, # {"name"=&gt;"France 2", "id"=&gt;5}, # {"name"=&gt;"France 3", "id"=&gt;6}] </code></pre> <p>Note</p> <pre><code>arr = list.group_by { |h| h["name"] }.values #=&gt; [[{"name"=&gt;"Germany", "id"=&gt;1}], # [{"name"=&gt;"USA", "id"=&gt;2}, {"name"=&gt;"USA", "id"=&gt;3}], # [{"name"=&gt;"France", "id"=&gt;4}, {"name"=&gt;"France", "id"=&gt;5}, # {"name"=&gt;"France", "id"=&gt;6}]] </code></pre> <p>Had I used <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-map" rel="nofollow">Enumerable#map</a> rather than <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-flat_map" rel="nofollow">Enumerable#flat_map</a>, the result would have been</p> <pre><code> [[{"name"=&gt;"Germany 1", "id"=&gt;1}], [{"name"=&gt;"USA 1", "id"=&gt;2}, {"name"=&gt;"USA 2", "id"=&gt;3}], [{"name"=&gt;"France 1", "id"=&gt;4}, {"name"=&gt;"France 2", "id"=&gt;5}, {"name"=&gt;"France 3", "id"=&gt;6}]] </code></pre> <p>Using <code>flat_map</code> is equivalent to inserting a splat in front of each of this array's elements.</p> <pre><code> [*[{"name"=&gt;"Germany 1", "id"=&gt;1}], *[{"name"=&gt;"USA 1", "id"=&gt;2}, {"name"=&gt;"USA 2", "id"=&gt;3}], *[{"name"=&gt;"France 1", "id"=&gt;4}, {"name"=&gt;"France 2", "id"=&gt;5}, {"name"=&gt;"France 3", "id"=&gt;6}]] </code></pre>