Abdo
Abdo

Reputation: 14071

Ruby `each_with_object` with index

I would like to do a.each_with_object with index, in a better way than this:

a = %w[a b c]
a.each.with_index.each_with_object({}) { |arr, hash|  
  v,i = arr
  puts "i is: #{i}, v is #{v}" 
}

i is: 0, v is a
i is: 1, v is b
i is: 2, v is c
=> {}

Is there a way to do this without v,i = arr ?

Upvotes: 48

Views: 20482

Answers (3)

ka8725
ka8725

Reputation: 2918

In your example .each.with_index is redundant. I found this solution:

['a', 'b', 'c'].each_with_object({}).with_index do |(el, acc), index|
  acc[index] = el
end
# => {0=>"a", 1=>"b", 2=>"c"}

Upvotes: 85

Cary Swoveland
Cary Swoveland

Reputation: 110755

You could replace your last line with

puts "i is: %d, v is %s" % arr.reverse

but, as @sawa suggested, disambiguating the array's argument is the thing to do here. I just mention this as something to be stored away for another day.

Upvotes: 1

sawa
sawa

Reputation: 168269

Instead of

|arr, hash|

you can do

|(v, i), hash|

Upvotes: 51

Related Questions