器-说明:使用define_method和define_sing
2019-10-03 本文已影响0人
稻草人_b788
一、使用define_method定义单例方法
一般而言对类使用define_method方法时,定义的都是实例方法。该方法需要接收方法名作为参数,并且接收一个代码块。
需要注意的是当使用{}
代码块而不是 do...end代码块时,需要将方法名带上括号,否则ruby不能正常解析语法。
class Apple
define_method(:hello) {
"hello,world"
}
define_method(:say) do |word|
"I say #{word}"
end
end
这样就在Apple类中定义了两个实例方法,分别是hello和say方法
可以这样调用:
a = Apple.new
a.hello
=> "hello,world"
a.say("nice weather today")
=> "I say nice weather today"
当然我们也可以使用define_method来定义单例方法:
1.定义类方法,可以这样做:
class << Apple #打开Apple类的单例类
define_method :show do
"I'm Apple's singleton class"
end
end
然后就可以直接调用这个类方法:
Apple.show
=> "I'm Apple's singleton class"
2.对实例定义单例方法,可以这样做:
class << a
define_method :talk do
"create a's singleton method"
end
end
a.talk
=> "create a's singleton method"
二、使用define_singleton_method定义单例方法
define_singleton_method方法可以直接定义单例方法(此处是类方法)
该方法需要接收方法名作为参数,并且接收一个代码块
class Human
define_singleton_method :run do |num|
"I can run #{num} km per hour"
end
end
然后调用这个单例方法:
Human.run(10)
=> "I can run 10 km per hour"
三、define_method和define_singleton_method的效能问题
使用define_method和define_singleton_method可以动态定义方法,但它们要比直接使用def关键字定义方法的效率慢。