How to use certain? (Super) with define_method

When I use define_methodfrom a block passed to an iterator, for some reason it defined?(super)never evaluates true.

See the example below. Note that this super(value)is a valid challenge, although it defined?thinks differently.

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!
+4
source share
1 answer

This is a bug in Ruby 1.9.3, which was fixed in 2.0.0-p0 but was never supported until 1.9.3. The error reported is not exactly the same, but fixing it most likely resolved this.

, , defined? super , Proc. .

Ruby 2.0 ( 2.1), , .

+1

All Articles