mutating the caller

Explain why the last line in the below code prints “hello world”. What does this demonstrate?


def change(param)
param << " world"
end

greeting = "hello"
change(greeting)

puts greeting

The last line here prints “hello world” because even though the variable greeting is set as “hello”, when the method was run it was given that variable as a parameter and the code in the method mutated the caller. This changed the orignal value of greeting to “hello world”. This demonstrates mutating the caller.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: