LAMagnotti LAMagnotti - 1 year ago 97
Ruby Question

Mutating Calling Objects in Ruby

Can someone explain why this prints "goodnight"? If you removed

string = "hello"

It would print "goodnight world" .

def a_method(string)
string = "hello"
string << " world"

bedtime = "goodnight"

puts bedtime

I understand that << mutates, but not why adding the = hello makes such a big difference?

Answer Source

In Ruby there's a difference between in-place operations and those that return a copy. Sometimes the name provides a hint, like gsub vs gsub!, but other times you just need to know, like <<.

What you're doing here is redefining which object string references so no permanent modification is made to the original reference.

The line string = "hello" does not mean that the original bedtime object reference changes.

If you wanted that effect you'd do string.replace("hello") which is an in-place reassignment of the string's content.

To find out what object you're referencing call object_id on the object in question. You'll notice here that with your code that value changes, but with replace it does not.

Ruby method arguments are passed by object reference which in practice is a lot like a pointer. If you're expecting that value to be passed by absolute reference that's not the case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download