我怎么能在 ruby 中进行类型转换

how could I do type casting in ruby

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

a = A.new
b = B.new

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

疯狂、毫无意义的方式:

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"

理智、惯用的方式:

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"