当我在传递给迭代器的块中使用define_method
时,由于某种原因,defined?(super)
永远不会计算为true
。
请参阅下面的示例。请注意,super(value)
是有效的通话,即使defined?
认为不是这样。
class A
def message=(val)
puts 'A says ' + val
end
end
class B < A
['message', 'warning'].each do |method|
define_method(method + '=') do |val|
puts 'B says ' + val
super(val) if defined?(super)
end
end
end
a = A.new
a.message = 'hello!' # A says hello!
b = B.new
b.message = 'hello!' # B says hello!
############################################
class B < A
['message', 'warning'].each do |method|
define_method(method + '=') do |val|
puts 'B says ' + val
super(val) rescue nil
end
end
end
b = B.new
b.message = 'hello!' # B says hello! A says hello!