0

I have an array:

arr = [a, ab, abc]

I want to make a hash, using the values of the array as the keys:

newhash = [a[1], ab[1], abc[1]]

I have tried:

arr.each do |r|
    newhash[r] == 1
end

to no avail.

How would I about accomplishing this in ruby?

4 Answers 4

1

If you are feeling like a one-liner, this will work as well

h = Hash[arr.collect { |v| [v, 1] } ]

collect is invoked once per element in the array, so it returns an array of 2-element arrays of key-value pairs.

Then this is fed to the hash constructor, which turns the array of pairs into a hash

Sign up to request clarification or add additional context in comments.

Comments

1

You could also use the #reduce method from Enumerable (which is included into the Array class).

new_hash = arr.reduce({}) { |hsh, elem| hsh[elem] = 1; hsh }

And your new_hash looks like this in Ruby:

{"a": 1, "ab": 1, "abc": 1}

Comments

0

== is comparison. = is assigning. So just modify == into =. It works.

newhash = {}
arr.each do |r|
  newhash[r] = 1
end

(I believe a, ab, abc are strings)

To learn more, this might help you. Array to Hash Ruby

Comments

0

You can do it like this:

ary = [[:foo, 1], [:bar, 2]]
Hash[ary] # => {:foo=>1, :bar=>2}

If you want to do it like you tried earlier, you want to initialize hash correctly:

ary = [:foo, :bar]
hash = {}
ary.each do |key|
  hash[key] = 1
end # => {:foo=>1, :bar=>2}

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.