Project

General

Profile

Bug #9139

each_with_index

Added by dostapn (Dima Ostapenko) over 5 years ago. Updated over 5 years ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
ruby -v:
ruby 2.0.0p247 (2013-06-27 revision 41674) [i686-linux]
[ruby-core:58493]

Description

Whats wrong with index?

Array.new(4, Hash.new).each_with_index{ |item, index| item["index"] = index; item["value"] = 10*index; p index;}
0
1
2
3
=> [{"index"=>3, "value"=>30},
{"index"=>3, "value"=>30},
{"index"=>3, "value"=>30},
{"index"=>3, "value"=>30}]

History

Updated by alexeymuranov (Alexey Muranov) over 5 years ago

What's wrong with index? :)

Updated by duerst (Martin Dürst) over 5 years ago

  • Status changed from Open to Rejected

Nothing is wrong with index.

Array.new(4, Hash.new) creates an array with four copies of one and the same new hash. Your code is the same as

h = Hash.new
[h, h, h, h].each_with_index{ |item, index| item["index"] = index; item["value"] = 10*index; p index;}

Maybe what you want is this:

Array.new(4) {|_| Hash.new}.each_with_index{ |item, index| item["index"] = index; item["value"] = 10*index; p index;}
0
1
2
3
-> [{"index"=>0, "value"=>0},
{"index"=>1, "value"=>10},
{"index"=>2, "value"=>20},
{"index"=>3, "value"=>30}]

Also available in: Atom PDF