ruby – 如何在类变量中定义的lambda / Proc中使用实例变量?
发布时间:2020-12-17 02:42:55 所属栏目:百科 来源:网络整理
导读:我写了以下代码: 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
我写了以下代码:
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哈希成为类变量并仍然能够访问特定的对象实例变量? 解决方法
您可以在调用lambda时使用
instance_exec 为lambda提供适当的上下文,查找注释以查看更改:
class Actions # Move the lambdas to a class variable,a COMMANDS constant # would work just as well and might be more appropriate. @@commands = { "ADD" => ->(name) { @people << name },"REMOVE" => ->(n = 0) { puts "Goodbye" },"OTHER" => ->(n = 0) { puts "Do Nothing" } } def initialize @people = [ ] end def run_command(cmd,*param) # Use instance_exec and blockify the lambdas with '&' # to call them in the context of 'self'. Change the # @@commands to COMMANDS if you prefer to use a constant # for this stuff. instance_exec(param,&@@commands[cmd]) if @@commands.key?(cmd) end def people @people end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |