Changing Objects Passed Into Methods – Ruby

When a variable is passed into a method, it may or may not be changed based on the operation that takes place inside the method.

For example:

def no_mutation(str)
  str + ", John?
end

words = "How are you"
no_mutation(words)

puts words    # => "How are you"

Notice how the “+” operator doesn’t change or mutate the “words” variable? That’s because “+” is not destructive. It concatenates “How are you” and “, John?” but that complete string isn’t assigned to anything nor the original object “How are you” changed by the “+” operator. If the line were changed to str = str + “, John?”, the str variable would then point to a new string object “How are you, John?” but it would not change the original string object that was passed into the method.

Now let’s look at the following code.

def mutation(str)
  str << ", John?
end

words = "How are you"
mutation(words)

puts words    # => "How are you, John?"

This time string object that “words” points to is changed by the method. That’s because the << in the method is destructive and mutates the object that is referenced by the variable.

Conclusion:

Depending on the operation going on in the method, the object passed in may or may not be changed. It’s a good reason to use irb to test your code and see what is happening to the objects in your methods.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s