0
a = ["ab", "dc", "vv", "dd"]
a.each_with_index.map { |v, i| { ("prefix_" + i.to_s).to_sym => v }}
 => [{:prefix_0=>"ab"}, {:prefix_1=>"dc"}, {:prefix_2=>"vv"}, {:prefix_3=>"dd"}]

I want to get a hash as a return value. How can I do this?

2
  • It is not clear what hash you want. Commented Aug 23, 2014 at 10:23
  • 2
    @AlexanderSupertramp Don't be Rude... Your question was not clear really. I took a wild guess. Commented Aug 23, 2014 at 10:26

2 Answers 2

4

This is one way :

a = ["ab", "dc", "vv", "dd"]
Hash[a.map.with_index { |v, i| ["prefix_#{i}".to_sym, v] }]
# => {:prefix_0=>"ab", :prefix_1=>"dc", :prefix_2=>"vv", :prefix_3=>"dd"}

In Ruby 2.1 >=, use Array#to_h as below :-

a.map.with_index { |v, i| ["prefix_#{i}".to_sym, v] }.to_h
Sign up to request clarification or add additional context in comments.

Comments

1

You can chain enumerators together, so another option is something like this:

 a.each_with_index.each_with_object({}) { |(v, i), h| h["prefix_#{i}"] = v }

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.