ruby variable as same object (pointers?)

前端 未结 7 1062
-上瘾入骨i
-上瘾入骨i 2021-01-01 03:22
>> a = 5
=> 5
>> b = a
=> 5
>> b = 4
=> 4
>> a
=> 5

how can I set \'b\' to actually be \'a\' so that in the exa

7条回答
  •  余生分开走
    2021-01-01 03:46

    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
    

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

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

    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 (=).

    Example with strings:

    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
    

    Example with arrays:

    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]
    

提交回复
热议问题