是否可以不为 lambda 分配上下文?
例如:
class Rule
def get_rule
return lambda {puts name}
end
end
class Person
attr_accessor :name
def init_rule
@name = "ruby"
Rule.new.get_rule.call() # should say "ruby" but say what object of class Rull, does not have variable name
# or self.instance_eval &Rule.new.get_rule
end
end
我的目标是 -> 没有上下文的存储过程对象,并在特定位置调用之前分配上下文。可能吗?
最佳答案
派对有点晚了,但这里有另一种方法,可以通过将上下文显式传递给规则来实现。
class Rule
def get_rule
return lambda{|context| puts context.name}
end
end
class Person
attr_accessor :name
def init_rule
@name = "ruby"
Rule.new.get_rule.call(self)
end
end
Person.new.init_rule
#=> ruby
关于Ruby 将上下文分配给 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7470508/