在Ruby中将基类转换为子类

时间:2013-02-21 10:09:15

标签: ruby

in ruby​​

class A
  @x = 1
  @y = 2
  attr_accessor :x, :y
end

class B < A
  @z = 3
  attr_accessor :z
end

a = A.new
b = B.new

[1]将A(a)的实例转换为B?不会失去任何A的成员价值 在c ++中会有static_cast,reinterpret_cast,“convert”操作符等。如何在ruby上执行此操作? (有没有捷径),例如

b = a.convert_to B
# b.x = 1
# b.y = 2
# b.z = 3

[2]如果有许多数据成员继承,如何使用值覆盖B(b)实例的每个继承数据成员值? (有内置的方法或快捷方式吗?)例如

a.x = 1
a.y = 2

b.x = 3
b.y = 4
b.z = 6

b.overwrite_all_inherited_method_from a
# b.x = 1
# b.y = 2
# b.z = 6

1 个答案:

答案 0 :(得分:1)

像这样的Smth?

class A
  attr_accessor :x, :y

  def copy other
    other.instance_variables.each do |v| 
      instance_variable_set v, other.instance_variable_get(v)
    end
  end
end

class B < A
  attr_accessor :z
end

a = A.new
a.x = 1
a.y = 2

b = B.new
b.z = 3

puts a.inspect, b.inspect
#<A:0x0000010127f3d8 @x=1, @y=2>
#<B:0x0000010127f3b0 @z=3>

b.copy a

puts a.inspect, b.inspect
#<A:0x0000010127f3d8 @x=1, @y=2>
#<B:0x0000010127f3b0 @z=3, @x=1, @y=2>