Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

ruby - Storing a proc inside an array inside a hash

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...