我怎么能在红宝石中打字

时间:2017-04-25 07:11:41

标签: ruby metaprogramming

我想在A的实例上执行B实例的方法,其中AB不相关,独立类。

a = A.new
b = B.new

b.<method_of_a>

2 个答案:

答案 0 :(得分:3)

class A
  def yay!
    puts "¡YAY!"
  end
end
b = A.new
A.instance_method(:yay!).bind(b).()
#⇒ "¡YAY!"

答案 1 :(得分:3)

疯狂,毫无意义的方式:

class A
  def a_method
    'I am instance of A'
  end
end

class B
  def method_missing(method_name)
    if method_name.to_s =~ /a_method/
      A.instance_method(method_name).bind(self).call
    else
      super
    end
  end
end

B.new.a_method
#=> "I am instance of A"

Sane,惯用的方式:

module CommonMethods
  def common_method
    'I am available for all includers'
  end
end

class A
  include CommonMethods
end

class B
  include CommonMethods
end

a = A.new
b = B.new

a.common_method
#=> "I am available for all includers"
b.common_method
#=> "I am available for all includers"