1

在红宝石中

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?在不丢失 C++ 中任何 A 的成员值的情况下,会有 static_cast、reinterpret_cast、“convert”运算符等。如何在 ruby​​ 上执行此操作?(有没有捷径),例如

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

[2] 如果继承了很多数据成员,如何使用a的值覆盖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
4

1 回答 1

1

像这样?

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>
于 2014-12-01T13:22:31.503 回答