send的使用:
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
send其实就是动态地根据名字调用函数,传递后面的内容作为调用参数,api函数原型为:
obj.send(symbol [, args...]) => obj
作为脚本语言,ruby自然也有eval这样的函数,除此之外,还有instance_eval和class_eval
instance_eval感觉就是取出对象的里的变量
class Klass
def initialize
@secret = 99
end
end
k = Klass.new
k.instance_eval { @secret } #=> 99
class_eval(alias module_eval)就比较重要了,实现类的动态性方面作用很大,rails的框架里就大量使用了class_eval来动态丰富类的成员
class Thing
end
a = %q{def hello() "Hello there!" end}
Thing.module_eval(a)
puts Thing.new.hello() => "Hello there!"
在rails里的action_controller.rb里 ActionController::Base.class_eval do include ActionController::Flash include ActionController::Filters 。。。。 end
最后
以上就是年轻方盒最近收集整理的关于ruby中的send,xxx_eval方法的全部内容,更多相关ruby中内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复