将函数存储在哈希中 [英] Store functions in hash

查看:49
本文介绍了将函数存储在哈希中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Ruby中您可以创建如下的哈希映射:

I know that in Ruby you can create hash maps like this:

hash = {"name"=>"John"}

但是可能有方法的哈希图:

But is it possible to have a hash map of methods:

hash = {"v"=> show_version}

,并在调用 hash ["v"] 时执行 show_version 函数,或返回传递给某些特殊方法的某种指针,以执行从哈希函数开始?

and when calling hash["v"] either to execute the show_version function, or to return some kind on pointer that passed to some special method, to execute the function from the hash?

我想要实现的是拥有一个方法的哈希图,而不是使用 case/when 构造,因为它对我来说太冗长了.

What I am trying to achieve, is to have a hash map of methods, instead of using a case/when construction, as it looks too verbose to me.

推荐答案

不完全像这样,不.您需要保留该方法的 Method 代理对象,并将其存储在 Hash :

Not exactly like this, no. You need to get a hold of the Method proxy object for the method and store that in the Hash:

hash = { 'v' => method(:show_version) }

您需要调用 Method 对象:

hash['v'].()

Method 鸭子类型 Proc ,因此您甚至可以将简单的 Proc s与 Method s一起存储在 Hash ,无需区分它们,因为它们的调用方式相同:

Method duck-types Proc, so you could even store simple Procs alongside Methods in the Hash and there would be no need to distinguish between them, because both of them are called the same way:

hash['h'] = -> { puts 'Hello' }
hash['h'].()
# Hello

这篇关于将函数存储在哈希中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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