在 Ruby 中,如何从数组中生成散列? [英] In Ruby, how do I make a hash from an array?

查看:22
本文介绍了在 Ruby 中,如何从数组中生成散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的数组:

arr = ["apples", "bananas", "coconuts", "watermelons"]

我还有一个函数 f ,它将对单个字符串输入执行操作并返回一个值.这个操作开销很大,所以想把结果记在hash里.

I also have a function f that will perform an operation on a single string input and return a value. This operation is very expensive, so I would like to memoize the results in the hash.

我知道我可以用这样的东西制作所需的散列:

I know I can make the desired hash with something like this:

h = {}
arr.each { |a| h[a] = f(a) }

我想要做的不是初始化 h,这样我就可以这样写:

What I'd like to do is not have to initialize h, so that I can just write something like this:

h = arr.(???) { |a| a => f(a) }

能做到吗?

推荐答案

假设你有一个名字很有趣的函数:"f"

Say you have a function with a funtastic name: "f"

def f(fruit)
   fruit + "!"
end

arr = ["apples", "bananas", "coconuts", "watermelons"]
h = Hash[ *arr.collect { |v| [ v, f(v) ] }.flatten ]

会给你:

{"watermelons"=>"watermelons!", "bananas"=>"bananas!", "apples"=>"apples!", "coconuts"=>"coconuts!"}

更新:

正如评论中提到的,Ruby 1.8.7 为此引入了更好的语法:

As mentioned in the comments, Ruby 1.8.7 introduces a nicer syntax for this:

h = Hash[arr.collect { |v| [v, f(v)] }]

这篇关于在 Ruby 中,如何从数组中生成散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆