Ruby - 将数组映射到哈希图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13017501/
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 05:28:28  来源:igfitidea点击:

Ruby - mapping an array to hashmap

rubyhashmap

提问by Ji Mun

I have an array, and a function that returns a value given a value. Ultimately I want to create a hashmap that has the values of the array as key value, and the result of f(key_value) as the value. Is there a clean, simple way, like similar to each/map of Array, of doing this using block?

我有一个数组和一个返回给定值的值的函数。最终我想创建一个哈希图,它以数组的值作为键值,并将 f(key_value) 的结果作为值。是否有一种干净,简单的方法,类似于数组的 each/map,使用块来执行此操作?

So something that is equivalent to

所以相当于

hsh = {}
[1,2,3,4].each do |x|
  hsh[x] = f(x)
end

but looks more similar to this, in that it's simple and one line?

但看起来更像这个,因为它很简单而且只有一行?

results = array.map { | x | f(x) }

采纳答案by Zach Kemp

You could also define the function as the hash's default value:

您还可以将该函数定义为散列的默认值:

hash = Hash.new {|hash, key| hash[key] = f(key) }

Then when you lookup a value, the hash will calculate and store it on the fly.

然后,当您查找一个值时,散列将即时计算并存储它。

hash[10]
hash.inspect #=> { 10 => whatever_the_result_is }

回答by Knotty66

Note that since Ruby 2.1.0 you can also use Array#to_h, like this:

请注意,从 Ruby 2.1.0 开始,您还可以使用Array#to_h,如下所示:

[1,2,3,4].map{ |x| [x, f(x)] }.to_h

回答by Sergio Tulentsev

You need each_with_object.

你需要each_with_object.

def f x
  x * 2
end

t = [1, 2, 3, 4].each_with_object({}) do |x, memo|
  memo[x] = f(x)
end

t # => {1=>2, 2=>4, 3=>6, 4=>8}

Another one:

另一个:

t2 = [1, 2, 3, 4].map{|x| [x, f(x)]}
Hash[t2] # => {1=>2, 2=>4, 3=>6, 4=>8}

回答by Matt Huggins

Check out the Hash::[]method.

查看Hash::[]方法。

Hash[ [1,2,3,4].collect { |x| [x, f(x)] } ]

回答by Timitry

Ruby 2.6.0 enables passing a block to the to_h-method. This enables an even shorter syntax for creating a hash from an array:

Ruby 2.6.0 允许将块传递给to_h-method。这为从数组创建哈希启用了更短的语法:

[1, 2, 3, 4].to_h { |x| [x, f(x)] }

回答by tokland

Using Facets' mash(method to convert enumerable to hashes):

使用 Facets 的mash(将可枚举转换为哈希的方法):

[1, 2, 3, 4].mash { |x| [x, f(x)] }

From Ruby 2.1:

从 Ruby 2.1 开始:

[1, 2, 3, 4].map { |x| [x, f(x)] }.to_h

回答by Tombart

You're looking for reduce()|inject()method:

您正在寻找reduce()|inject()方法

elem = [1,2,3,4]
h = elem.reduce({}) do |res, x|
  res[x] = x**2
  res
end

puts h

The argument passed to reduce({})is the initial value of an intermediate object that is passed to the block as resvariable. In each iteration we're adding new pair key: valueto the resHash and returing the Hash to be used in next iteration.

传递给的参数reduce({})是作为res变量传递给块的中间对象的初始值。在每次迭代中,我们都将新对添加key: valueresHash 并返回要在下一次迭代中使用的 Hash。

The method above precomputes a very practical hash of squared values:

上面的方法预先计算了一个非常实用的平方值散列:

{1=>1, 2=>4, 3=>9, 4=>16}