I'm trying to create two methods, one of which will destructively add "i" to any string, and one of which will do the same non-destructively.
def add_i(string)
new_string = string + "i"
end
def add_i!(string)
string = string + "i"
end
My questions are:
Both of these methods are non-destructive, even though I do not replace the argument in the second method with a new variable. Why?
In general, how do I convert a non-destructive method into a destructive one and vice versa?
The answer lies in the scope of the vars and the behavior of the methods/operators. the left hand side (left to the = )string inside add_i! is a different string than the one passed in (the right side string and the method arg). The old string continues to live on but the string var points to the new one.
to make the 2nd method "destructive" you could do something like:
def add!(string)
string << "i"
end
as a rule of the thumb, you need to understand if the methods/operators you are applying are operating on the data itself or are returning a copy of the data (for example the '+' upstairs returns a copy)
an easy way of dealing with string and making sure you don't destroy the data is to use dup() on whatever is passed in and after that operate on the copy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With