可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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"}