Ruby - 将数组映射到hashmap

Ji *_*Mun 53 ruby hashmap

我有一个数组,以及一个返回给定值的值的函数.最后,我想创建一个hashmap,它将数组的值作为键值,并将f(key_value)的结果作为值.是否有一个干净,简单的方法,就像使用块的每个/ map一样,这样做?

所以相当于的东西

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

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

results = array.map { | x | f(x) }
Run Code Online (Sandbox Code Playgroud)

Kno*_*y66 111

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

[1,2,3,4].map{ |x| [x, f(x)] }.to_h
Run Code Online (Sandbox Code Playgroud)


Zac*_*emp 28

您还可以将函数定义为哈希的默认值:

hash = Hash.new {|hash, key| hash[key] = f(key) }
Run Code Online (Sandbox Code Playgroud)

然后,当您查找值时,哈希将计算并动态存储它.

hash[10]
hash.inspect #=> { 10 => whatever_the_result_is }
Run Code Online (Sandbox Code Playgroud)


Ser*_*sev 23

你需要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}
Run Code Online (Sandbox Code Playgroud)

另一个:

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


Mat*_*ins 21

查看Hash :: []方法.

Hash[ [1,2,3,4].collect { |x| [x, f(x)] } ]
Run Code Online (Sandbox Code Playgroud)


Tim*_*try 10

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

[1, 2, 3, 4].to_h { |x| [x, f(x)] }
Run Code Online (Sandbox Code Playgroud)


tok*_*and 8

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

[1, 2, 3, 4].mash { |x| [x, f(x)] }
Run Code Online (Sandbox Code Playgroud)

来自Ruby 2.1:

[1, 2, 3, 4].map { |x| [x, f(x)] }.to_h
Run Code Online (Sandbox Code Playgroud)