本文介绍了红宝石变量作为同一对象(指针?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>> a = 5
=> 5
>> b = a
=> 5
>> b = 4
=> 4
>> a
=> 5

如何将'b'设置为'a',因此在示例中,变量a也将变为4.谢谢.

how can I set 'b' to actually be 'a' so that in the example, the variable a will become four as well. thanks.

推荐答案

class Ref
  def initialize val
    @val = val
  end

  attr_accessor :val

  def to_s
    @val.to_s
  end
end

a = Ref.new(4)
b = a

puts a   #=> 4
puts b   #=> 4

a.val = 5

puts a   #=> 5
puts b   #=> 5

执行b = a时,b指向与a相同的对象(它们具有相同的object_id).

When you do b = a, b points to the same object as a (they have the same object_id).

执行a = some_other_thing时,a将指向另一个对象,而b保持不变.

When you do a = some_other_thing, a will point to another object, while b remains unchanged.

对于Fixnumniltruefalse,如果不更改object_id,则无法更改该值.但是,您可以更改其他对象(字符串,数组,哈希等)而无需更改object_id,因为您不使用赋值(=).

For Fixnum, nil, true and false, you cannot change the value without changing the object_id. However, you can change other objects (strings, arrays, hashes, etc.) without changing object_id, since you don't use the assignment (=).

带有字符串的示例:

a = 'abcd'
b = a

puts a  #=> abcd
puts b  #=> abcd

a.upcase!          # changing a

puts a  #=> ABCD
puts b  #=> ABCD

a = a.downcase     # assigning a

puts a  #=> abcd
puts b  #=> ABCD

数组示例:

a = [1]
b = a

p a  #=> [1]
p b  #=> [1]

a << 2            # changing a

p a  #=> [1, 2]
p b  #=> [1, 2]

a += [3]          # assigning a

p a  #=> [1, 2, 3]
p b  #=> [1, 2]

这篇关于红宝石变量作为同一对象(指针?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:49