0
0
Rubyprogramming~15 mins

Immutable data with freeze in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Immutable data with freeze
📖 Scenario: You are working on a simple Ruby program that manages a list of favorite fruits. To avoid accidental changes to this list later in the program, you want to make the list immutable.
🎯 Goal: Create a frozen array of fruits so that the list cannot be changed after creation. Then, try to add a new fruit to see what happens.
📋 What You'll Learn
Create an array called fruits with the exact values 'apple', 'banana', and 'cherry'
Create a variable called immutable_fruits that holds the frozen version of fruits
Attempt to add 'orange' to immutable_fruits using the push method
Print the immutable_fruits array
💡 Why This Matters
🌍 Real World
Freezing data helps prevent accidental changes in programs, which is important in many real-world applications like configuration settings or constant values.
💼 Career
Understanding immutability and error handling is useful for writing safer, more reliable Ruby code in software development jobs.
Progress0 / 4 steps
1
Create the initial array of fruits
Create an array called fruits with the exact values 'apple', 'banana', and 'cherry'.
Ruby
Need a hint?

Use square brackets [] to create an array and separate items with commas.

2
Freeze the array to make it immutable
Create a variable called immutable_fruits that holds the frozen version of the fruits array using the freeze method.
Ruby
Need a hint?

Use freeze method on the array to make it immutable.

3
Try to add a new fruit to the frozen array
Use the push method to try to add 'orange' to the immutable_fruits array.
Ruby
Need a hint?

Use push method on immutable_fruits. Wrap it in begin...rescue to catch the error.

4
Print the frozen array and error message
Print the immutable_fruits array and then print the error_message variable to show the error caused by trying to modify the frozen array.
Ruby
Need a hint?

Use puts to print the array and the error message. Use inspect to show the array nicely.