要散列的 Ruby 数组:每个元素都是键并从中派生出值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9433678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:49:06  来源:igfitidea点击:

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

ruby

提问by lulalala

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?

我有一个字符串数组,想从中得到一个散列。数组的每个元素都是键,我想根据该键计算出值。有没有 Ruby 的方式来做到这一点?

For example:

例如:

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

['a','b']转换为 {'a'=>'A','b'=>'B'}

采纳答案by aidan

Ruby's each_with_objectmethod is a neat way of doing what you want

Ruby 的each_with_object方法是做你想做的事情的一种巧妙的方式

['a', 'b'].each_with_object({}) { |k, h| h[k] = k.upcase }

回答by Ricardo Acras

You can:

你可以:

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

回答by brad

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

回答by Kassym Dorsel

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

回答by Mark Thomas

Here's another way:

这是另一种方式:

a.zip(a.map(&:upcase)).to_h

#=>{"a"=>"A", "b"=>"B"}

回答by Jens Tinfors

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

回答by Ismael Abreu

Not sure if this is the real Ruby way but should be close enough:

不确定这是否是真正的 Ruby 方式,但应该足够接近:

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

回答by Joshua Pinter

.mapand .to_h

.map.to_h

[ 'a', 'b' ].map{ |element| [ element, element.upcase ] }.to_h
#=> {"a"=>"A", "b"=>"B"}