0

I'm clearly not quite understanding pass by value properly.

irb(main):001:0> a="UPPER CASE STRING"
=> "UPPER CASE STRING"
irb(main):002:0> b=a
=> "UPPER CASE STRING"
irb(main):003:0> a
=> "UPPER CASE STRING"
irb(main):004:0> b
=> "UPPER CASE STRING"
irb(main):005:0> b.downcase
=> "upper case string"
irb(main):006:0> a
=> "UPPER CASE STRING"
irb(main):007:0> b.downcase!
=> "upper case string"
irb(main):008:0> b
=> "upper case string"
irb(main):009:0> a
=> "upper case string"
irb(main):010:0>

Why is a lowercase, if pass by value then isn't b a copy of a ?

Is this because a is a (reference|pointer) to a String object and therefore b is a copy of the pointer not the object ?

Dean Smith
  • 2,163
  • 3
  • 21
  • 23

2 Answers2

6

Every object in Ruby has its own id. You can see the same using #object_id. Follow code :

a = "UPPER CASE STRING"
b = a
a.object_id # => 70041560
b.object_id # => 70041560

b and a pointing to the same object. b.downcase returns a copy of receiver with all uppercase letters replaced with their lowercase counterparts, not downcased the original string object. That's the reason after b.downcase, you didn't see the same change in a, while you were inspecting a in irb. But if you also inpect b, after b.downcase, you would also see the output of b as "UPPER CASE STRING".

b.downcase.object_id # => 78657980

But b.downcase! changed the original string object. As you modified the original receiver string object, thus b and a both now will output as "upper case string".

b.downcase!.object_id # => 70041560
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
2

Is this because a is a (reference|pointer) to a String object and therefore b is a copy of the pointer not the object ?

Yes.

BroiSatse
  • 44,031
  • 8
  • 61
  • 86
  • http://stackoverflow.com/questions/1872110/is-ruby-pass-by-reference-or-by-value, 2nd answer seems to explain this quite well. I'm going to close this. – Dean Smith Apr 09 '14 at 11:38