Ruby array to hash: each element is a key and derives a value from it

I have an array of strings and want to make a hash from it. Each element of the array will be a key, and I want the value to be computed from this key. Is there a way for Ruby to do this?

For example:

['a','b'] to convert to {'a'=>'A','b'=>'B'}

+19
ruby
Feb 24 '12 at 15:50
source share
7 answers

You can:

 a = ['a', 'b'] Hash[a.map {|v| [v,v.upcase]}] 
+48
Feb 24 '12 at 16:11
source share
 %w{abc}.reduce({}){|a,v| a[v] = v.upcase; a} 
+21
Feb 24 '12 at 16:15
source share

Here's a naive and simple solution that converts the current character to a character to be used as a key. And just for fun, he capitalizes value. :)

 h = Hash.new ['a', 'b'].each {|a| h[a.to_sym] = a.upcase} puts h # => {:a=>"A", :b=>"B"} 
+4
Feb 24 2018-12-12T00:
source share

Whatever way you look at it, you will need to iterate the original array. Here's another way:

 a = ['a', 'b', 'c'] h = Hash[a.collect {|v| [v, v.upcase]}] #=> {"a"=>"A", "b"=>"B", "c"=>"C"} 
+3
Feb 24 '12 at 16:08
source share

Not sure if this is a real Ruby method, 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"} 
+1
Feb 24 2018-12-12T00:
source share

Ruby each_with_object method is a neat way to do what you want

 ['a', 'b'].each_with_object({}) { |k, h| h[k] = k.upcase } 
+1
Jul 31 '17 at 4:28
source share

Here's another way:

 a.zip(a.map(&:upcase)).to_h #=>{"a"=>"A", "b"=>"B"} 
0
Jun 11 '17 at 2:19 on
source share



All Articles