产量<<自在类方法 [英] Yield in class << self in class method
问题描述
我想创建一个类方法,它接受一个方法定义块并将其注入到类中.现在,self
确实是 Tom
对象,所以 class <<self
确实打开了它,但是 yield
似乎不起作用.我的理论知识不是那么深,所以我不确定为什么这不起作用.我可能完全错了,所以请随时讨论替代方案.
I want to create a class method that takes a block of method definitions and injects it into the class. Now, self
is indeed the Tom
object so class << self
does open it up, but yield
doesn't seem to work. My theoretical knowledge is not that deep, so I am not sure why this is not working. I might be getting this totally wrong, so feel free to discuss alternatives.
class Tom < Person
mega_methods do
def hiya!
puts 'hiYA!'
end
end
end
class Person
def self.mega_methods
...
class << self
yield
end
end
end
Tom.hiya!
我知道我可以使用 class << 在
或者我可以包含 Tom
中定义方法.selfclass <<self
在块中.
I am aware I could just define the methods in Tom
using class << self
or that I could include class << self
in the block.
我也想出了这个替代方案:
I also figured out this alternative:
def self.mega_methods &block
if block_given?
extension = Module.new(&Proc.new)
self.extend(extension)
end
end
这个问题更多的是帮助我理解 Ruby 的工作原理,而不是解决一个特定的问题.
This question is more about helping me understand the workings of Ruby rather than solving a specific issue.
推荐答案
这有点奇怪,但如果您正在探索 Ruby,那就没问题了.
It's a little bit weird, but OK if you are exploring Ruby.
class Person
puts "evaluating Person's body ..."
def self.mega_methods
puts 'in Person#self.mega_methods, about to yield ...'
yield
end
end
class Tom < Person
puts "evaluating Tom's body ..."
print 'Tom.singleton_methods : '; p Tom.singleton_methods
mega_methods do
puts 'in Tom, about to define self.hiya!'
def self.hiya!
puts 'hiYA!'
end
end
print 'Tom.singleton_methods : '; p Tom.singleton_methods
end
Tom.hiya!
执行:
$ ruby -w t.rb
evaluating Person's body ...
evaluating Tom's body ...
Tom.singleton_methods : ["mega_methods"]
in Person#self.mega_methods, about to yield ...
in Tom, about to define self.hiya!
Tom.singleton_methods : ["mega_methods", "hiya!"]
hiYA!
请注意,按照惯例,方法名称中的感叹号是为销毁方法保留的,例如修改接收者字符串的 String#sub!
.
Note that the exclamation point in the name of a method is, by convention, reserved for destroying methods, such as String#sub!
which modifies the receiver string.
另见 什么是 def `self.function` 名称是什么意思?
一切都是为了自己!
class Person2
def self.mega_methods
print 'in Person2 self='; p self
class << self
print 'in class << self self='; p self
yield
end
end
end
class Tom2 < Person2
mega_methods do
puts "in Tom2, about to define self.hiya! for self=#{self}"
def self.hiya!
puts 'hiYA!'
end
def hi
puts 'hi'
end
end
end
print 'Tom2.singleton_methods : '; p Tom2.singleton_methods
print 'Tom2.instance_methods : '; p Tom2.instance_methods(false)
Tom2.hiya!
Tom2.new.hi
执行:
$ ruby -w t2.rb
in Person2 self=Tom2
in class << self self=#<Class:Tom2>
in Tom2, about to define self.hiya! for self=Tom2
Tom2.singleton_methods : ["mega_methods", "hiya!"]
Tom2.instance_methods : ["hi"]
hiYA!
hi
这篇关于产量<<自在类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!