如何使用类变量中定义的 lambda/Proc 中的实例变量?
我编写了以下代码:
class Actions
def initialize
@people = []
@commands = {
"ADD" => ->(name){@people << name },
"REMOVE" => ->(n=0){ puts "Goodbye" },
"OTHER" => ->(n=0){puts "Do Nothing" }
}
end
def run_command(cmd,*param)
@commands[cmd].call param if @commands.key?(cmd)
end
def people
@people
end
end
act = Actions.new
act.run_command('ADD','joe')
act.run_command('ADD','jack')
puts act.people
这是可行的,但是,当 @commands
哈希是类变量时,哈希内的代码不知道 @people
数组。
如何使 @commands 哈希成为类变量并且仍然能够访问特定的对象实例变量?
I wrote the following code:
class Actions
def initialize
@people = []
@commands = {
"ADD" => ->(name){@people << name },
"REMOVE" => ->(n=0){ puts "Goodbye" },
"OTHER" => ->(n=0){puts "Do Nothing" }
}
end
def run_command(cmd,*param)
@commands[cmd].call param if @commands.key?(cmd)
end
def people
@people
end
end
act = Actions.new
act.run_command('ADD','joe')
act.run_command('ADD','jack')
puts act.people
This works, however, when the @commands
hash is a class variable, the code inside the hash doesn't know the @people
array.
How can I make the @commands
hash be a class variable and still be able to access the specific object instance variables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
instance_exec
来当您调用 lambda 时,为它们提供适当的上下文,查找注释以查看更改:You could use
instance_exec
to supply the appropriate context for the lambdas when you call them, look for the comments to see the changes:编辑遵循@VictorMoroz和@mu的建议:
或者
EDIT Following @VictorMoroz's and @mu's recommendations:
Or