Reputation: 17981
I have an array of strings, and want to make a hash out of it. Each element of the array will be the key, and I want to make the value being computed from that key. Is there a Ruby way of doing this?
For example:
['a','b']
to convert to {'a'=>'A','b'=>'B'}
Upvotes: 30
Views: 35655
Reputation: 9576
Ruby's each_with_object
method is a neat way of doing what you want
['a', 'b'].each_with_object({}) { |k, h| h[k] = k.upcase }
Upvotes: 9
Reputation: 4139
From Rails 6.x, you can use Enumerable#index_with
:
irb(main):002:0> ['a', 'b'].index_with { |s| s.upcase }
=> {"a"=>"A", "b"=>"B"}
Upvotes: 8
Reputation: 47531
.to_h
[ 'a', 'b' ].to_h{ |element| [ element, element.upcase ] }
#=> {"a"=>"A", "b"=>"B"}
Thanks to @SMAG for the refactor suggestion!
Upvotes: 5
Reputation: 37517
Here's another way:
a.zip(a.map(&:upcase)).to_h
#=>{"a"=>"A", "b"=>"B"}
Upvotes: 6
Reputation: 16730
Not sure if this is the real Ruby way but should be close enough:
hash = {}
['a', 'b'].each do |x|
hash[x] = x.upcase
end
p hash # prints {"a"=>"A", "b"=>"B"}
As a function we would have this:
def theFunk(array)
hash = {}
array.each do |x|
hash[x] = x.upcase
end
hash
end
p theFunk ['a', 'b', 'c'] # prints {"a"=>"A", "b"=>"B", "c"=>"C"}
Upvotes: 1
Reputation: 880
Here's a naive and simple solution that converts the current character to a symbol to be used as the key. And just for fun it capitalizes the value. :)
h = Hash.new
['a', 'b'].each {|a| h[a.to_sym] = a.upcase}
puts h
# => {:a=>"A", :b=>"B"}
Upvotes: 4
Reputation: 4843
Which ever way you look at it you will need to iterate the initial array. Here's another way :
a = ['a', 'b', 'c']
h = Hash[a.collect {|v| [v, v.upcase]}]
#=> {"a"=>"A", "b"=>"B", "c"=>"C"}
Upvotes: 5