>> a = 5
=> 5
>> b = a
=> 5
>> b = 4
=> 4
>> a
=> 5
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
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]
                        You can't. Variables hold references to values, not references to other variables.
Here's what your example code is doing:
a = 5 # Assign the value 5 to the variable named "a".
b = a # Assign the value in the variable "a" (5) to the variable "b".
b = 4 # Assign the value 4 to the variable named "b".
a # Retrieve the value stored in the variable named "a" (5).
See this article for a more in-depth discussion of the topic: pass by reference or pass by value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With