Welcome to day 25 of the 49 Days of Ruby! 🎉
Today is all about freezing things! No, we're not going to freeze you, personally, but we are going to talk about mutability and immutability.
What are these terms and what do they mean for my coding journey in Ruby?
When something is mutable it means that it can be changed. When something is immutable it means that it cannot be changed.
For example, let's take a look at the following code:
first_coffee = "espresso" second_coffee = first_coffee > puts second_coffee # => "espresso" second_coffee = "E" # => "Espresso" > puts first_coffee # => "Espresso"
Did you notice how when we modified the first letter of
second_coffee it also modified the first letter of
We probably do not want that behavior! We want to treat
first_coffee as unchangeable by cloning the first copy as the value of the second variable instead:
second_coffee = first_coffee.clone
Now, we can modify
second_coffee and not touch the
How can we turn a
mutable thing into an
immutable thing? Welcome to the
first_coffee = ["americano"].freeze first_coffee = "Espresso" # => FrozenError (can't modify frozen Array: ["americano"])
#freeze method does not work on strings themselves but on objects. Hence, we created an array and put the string inside of it, and called
#freeze on that.
The result when we tried to modify that is an exception:
What do you think some of the benefits of mutability and immutability are?
Share your ideas with the community using the hashtag #49daysofruby!
Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.
Top comments (0)