Store functions in hash

孤者浪人 提交于 2021-02-08 02:10:51

问题


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}

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?

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.


回答1:


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

And you need to call the Method object:

hash['v'].()

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


来源:https://stackoverflow.com/questions/27645773/store-functions-in-hash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!