Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何使用defined?(super)和define_方法_Ruby_Metaprogramming - Fatal编程技术网

Ruby 如何使用defined?(super)和define_方法

Ruby 如何使用defined?(super)和define_方法,ruby,metaprogramming,Ruby,Metaprogramming,当我从传递给迭代器的块中使用define\u方法时,由于某种原因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

当我从传递给迭代器的块中使用
define\u方法时,由于某种原因
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!
A类
def消息=(val)
将“A”表示+val
结束
结束
B类