I apologize for the excessive length, I just wanted to make sure I actually understand what's going on here. This is a follow up on my previous two questions Does 'upcase!' not mutate a variable in Ruby? and Destructive and non destructive methods in Ruby.
def changeMe(string)
string + "?"
end
phrase = "how are you"
puts changeMe(phrase) #how are you?
puts phrase #how are you
When changeMe
is invoked with the phrase
passed in as an argument, the parameter string
points to the same object as phrase
. When we change the line to string + "?"
we are creating a new object different from the one the string parameter points to, the same if we assigned the newly created object to a variable.
def changeMe(string)
string += "?"
end
phrase = "how are you"
puts changeMe(phrase) #how are you?
puts phrase #how are you
If I do this -
def changeMe(string)
string + "?"
string.capitalize!
end
phrase = "how are you"
puts changeMe(phrase) #How are you
puts phrase #How are you
When changeMe
is invoked with phrase
passed in as an argument, the string + "?"
creates a new object different from the one #capitalize!
is called on in the next line. #capitalize!
is called on the object that the variable phrase
is referencing, the same object the string parameter points to but not the same object returned by string + ?
. If we reassign it to a variable,
def changeMe(string)
string += "?"
string.capitalize!
end
phrase = "how are you"
puts changeMe(phrase) #How are you?
puts phrase #how are you
string += "?"
will create a new object that is assigned to a variable called string
. That new object has #capitalize!
called on it. The method is invoked with phrase
passed in as an argument and returns a new object different from the one the variable phrase
references so the original value for the variable phrase
is unchanged.
Are there flaws or misconceptions in my logic. Am I accurately explaining/understanding things?