49

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 ?

4
  • What is hash doing? Commented Feb 12, 2014 at 16:42
  • 4
    Why not just each_with_object({}).with_index?! Commented Feb 12, 2014 at 16:46
  • Yea, this is what I will use now that I know I can group values inside between || =) Commented Feb 12, 2014 at 16:48
  • 4
    Good one, @toro2. Readers should note that here the block variables would be |(e,h),i|, where e is the element of the array a, h is the hash object being created and returned and i is the index. map.with_index is another common use of with_index. When you can't tack with_index to the end of an Enumerable method, you can precede it with each_with_index, rather than each.with_index. Commented Feb 12, 2014 at 19:11

4 Answers 4

86

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"}
Sign up to request clarification or add additional context in comments.

Comments

52

Instead of

|arr, hash|

you can do

|(v, i), hash|

3 Comments

This is wrong, the answer below from @ka8725 is correct, it should be |(v, hash), i|, not |(v, i), hash|
I don't understand how a wrong answer can have so many votes 👎
both answers are correct as @sawa refers to a.each.with_index.with_object and @ka8725's answer refers to each_with_object({}).with_index
1

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.

1 Comment

Sure can :-) ... Sawa got me what I was looking for... I wanted a shortcut for assignment :-)
0

array.each_with_index.to_h

  • each_with_index gives you [element, index] pairs.

  • to_h converts an array of pairs ([key, value]) into a H

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.