Search code examples
rubyenumerable

Enumerator: collect method with two parameters


I have this code:

users = ["foo", "bar"]
users.collect { |item, value = []| value << {:name => item} }.flatten

That is working like the wind in ruby-1.9.2:

=> [{:name=>"foo"}, {:name=>"bar"}]

But this does not work in ruby-1.8.7 because it does not like collect getting two parameters:

SyntaxError: compile error
(irb):2: syntax error, unexpected '=', expecting '|'
users.collect { |item, value = []| value << {:name => item} }.flatten

Reading the documentation that's true, collect does not expect two parameters, but it's working in ruby 1.9.2. So am I missing something, my Array/Enumerable is being patched in some weird way or is the documentation wrong?


Solution

  • I think you are missing something. This is what you want to do, and it works in both 1.9 and 1.8:

    users.collect { |i| { :name => i } }