1

I have an array and I want to convert it to a hash. I want the array elements to be keys, and all values to be the same.

Here is my code:

h = Hash.new
myarr.each do |elem|
  h[elem] = 1
end

One alternative would be the following. I don't think it's very different from the solution above.

h = Hash[ *myarr.collect { |elem| [elem, 1] }.flatten ]

Is there a better way I can do this?

5 Answers 5

6

The code OP wrote, can also be written as :-

a = %w(a b c d)
Hash[a.each_with_object(1).to_a]
# => {"a"=>1, "b"=>1, "c"=>1, "d"=>1}

And if you have Ruby version >= 2.1, then

a.each_with_object(1).to_h
# => {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
Sign up to request clarification or add additional context in comments.

Comments

3

First of all, Hash[] is quite happy to get an array-of-arrays so you can toss out the splat and flatten and just say this:

h = Hash[myarr.map { |e| [ e, 1 ] }]

I suppose you could use each_with_object instead:

h = myarr.each_with_object({}) { |e, h| h[e] = 1 }

Another option would be to zip your myarr with an appropriate array of 1s and then feed that to Hash[]:

h = Hash[myarr.zip([1] * myarr.length)]

I'd probably use the first one though.

Comments

3

If you are using Ruby 2.1:

myarr.map{|e| [e,1]}.to_h

Another clever way (from comment by @ArupRakshit):

myarr.product([1]).to_h

6 Comments

The OP clearly said they are using Ruby 1.9.3 (Although I moved that to ruby-1.9 tag).
Ah, OK. Perhaps I'll delete.
I'd leave it here, people will presumably come across this question when they're just looking for general Ruby solutions so this is a worthwhile answer.
You're right, @Arup. I knew that :) Fixed.
+1 for telling my way is clever. :-) The fact is I also knew that, but as you wrote 2.0, I lost my confidence, and had to go to the doco for double checking it..
|
1

Here is another option, using cycle:

Hash[a.zip([1].cycle)]

1 Comment

I also really like this answer for its simplicity.
-1
a.each_with_object({}){|e, h| h[e] = 1}

3 Comments

Note: This was earlier than another answer that posts exactly the same solution without hesitation.
7s earlier because I took the time to correct their misunderstanding about the Hash[] arguments and I took the time to include other solutions.
Timeliness in itself shouldn't translate to votes. Once this post is 2 years old, nobody will care when the answers arrived. However, if it indicated someone was taking credit for someone else's answer, it would be a problem. This is clearly not the case here.

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.