Ruby array to hash: each element the key and derive value from it

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

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'}

回答1:

You can:

a = ['a', 'b'] Hash[a.map {|v| [v,v.upcase]}] 


回答2:

%w{a b c}.reduce({}){|a,v| a[v] = v.upcase; a} 


回答3:

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"} 


回答4:

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"} 


回答5:

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"} 


回答6:

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 } 


回答7:

Here's another way:

a.zip(a.map(&:upcase)).to_h  #=>{"a"=>"A", "b"=>"B"} 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!