Storing a proc inside an array inside a hash

拟墨画扇 提交于 2021-01-29 18:19:39

问题


I am still working on my text adventure. I am having trouble with the use/with function. It is meant to call a Hash in which the key is the used object and the content includes an array; the first element in the array is the target object, and the second a Proc that will be executed if that relation turns to match the arguments for the use/with function.

Please, may you clarify me how I can store a code block inside an array inside a hash so I can recall it later depending on the objects that are being combined?

Here is my use function that takes "use object with with":

    def use(object, with)
    if INTERACTIONS[object][0] == with
        INTERACTIONS[object][1]
    end
end

And this is how I defined the relations (so far there is just one):

INTERACTIONS = {"key" => ["clock", p = Proc.new{puts "You open the clock!"}]}

Whenever I type

use key with clock

it returns nothing but a new prompt line.


回答1:


You forgot to .call the proc:

INTERACTIONS = {"key" => ["clock", Proc.new {puts "You open the clock!"}]}

def use(object, with)
  if INTERACTIONS[object][0] == with
    INTERACTIONS[object][1].call  # procs need to be `call`ed :)
  end
end


use("key", "clock") # => You open the clock!


来源:https://stackoverflow.com/questions/20053112/storing-a-proc-inside-an-array-inside-a-hash

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