Ruby将上下文分配给lambda吗? [英] Ruby assign context to lambda?
本文介绍了Ruby将上下文分配给lambda吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以不将上下文分配给lambda?
Is it possible not to assign context to 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
我的目标是->没有上下文的存储过程对象,并在调用之前在特定位置分配上下文.有可能吗?
My target is -> stored procedure objects without contexts, and assign context before call in specific places. Is it possible?
推荐答案
是的,但是要小心一点,这个确实很容易滥用.我个人会担心这样的代码.
Yeah, but be careful with it, this one is really easy to abuse. I would personally be apprehensive of code like this.
class Rule
def get_rule
Proc.new { puts name }
end
end
class Person
attr_accessor :name
def init_rule
@name = "ruby"
instance_eval(&Rule.new.get_rule)
end
end
这篇关于Ruby将上下文分配给lambda吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文