Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby `each_with_object` with index

Tags:

ruby

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 ?

like image 391
Abdo Avatar asked Feb 12 '14 16:02

Abdo


2 Answers

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"}
like image 188
ka8725 Avatar answered Oct 29 '22 20:10

ka8725


Instead of

|arr, hash|

you can do

|(v, i), hash|
like image 52
sawa Avatar answered Oct 29 '22 19:10

sawa