12nm
12nm

Reputation: 41

How do I create a hash where the keys are values from an array Ruby

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?

Upvotes: 0

Views: 205

Answers (4)

Dave N
Dave N

Reputation: 398

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}

Upvotes: 1

mrosales
mrosales

Reputation: 1568

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

Upvotes: 1

dredozubov
dredozubov

Reputation: 725

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}

Upvotes: 0

shirakia
shirakia

Reputation: 2409

== 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

Upvotes: 0

Related Questions