DEV Community

Cover image for 49 Days of Ruby: Day 25 - Mutable and Immutable Objects
Ben Greenberg
Ben Greenberg

Posted on

49 Days of Ruby: Day 25 - Mutable and Immutable Objects

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[0] = "E"
# => "Espresso"

> puts first_coffee
# => "Espresso"
Enter fullscreen mode Exit fullscreen mode

Did you notice how when we modified the first letter of second_coffee it also modified the first letter of first_coffee?

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
Enter fullscreen mode Exit fullscreen mode

Now, we can modify second_coffee and not touch the first_coffee.

How can we turn a mutable thing into an immutable thing? Welcome to the #freeze method!

first_coffee = ["americano"].freeze

first_coffee[0] = "Espresso"

# => FrozenError (can't modify frozen Array: ["americano"])
Enter fullscreen mode Exit fullscreen mode

The #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: FrozenError.

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)