0
0
Rubyprogramming~15 mins

Rescue modifier (inline form) in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Rescue Modifier (Inline Form) in Ruby
📖 Scenario: Imagine you are writing a small program that tries to convert user input into a number. Sometimes, the input might not be a valid number, and your program should handle that gracefully without crashing.
🎯 Goal: You will build a Ruby program that uses the rescue modifier (inline form) to handle errors when converting strings to integers.
📋 What You'll Learn
Create a variable called user_input with the exact string value "abc"
Create a variable called number that tries to convert user_input to an integer using Integer(user_input) but uses the rescue modifier to assign 0 if an error occurs
Use the rescue modifier (inline form) exactly as expression rescue value
Print the value of number using puts
💡 Why This Matters
🌍 Real World
When accepting user input, programs often need to handle invalid data without crashing. Rescue modifier helps keep programs running smoothly by providing fallback values.
💼 Career
Understanding error handling is important for writing robust Ruby applications, especially in web development and scripting.
Progress0 / 4 steps
1
Create the user input variable
Create a variable called user_input and set it to the string "abc" exactly.
Ruby
Need a hint?

Use = to assign the string "abc" to user_input.

2
Use rescue modifier to convert input
Create a variable called number that tries to convert user_input to an integer using Integer(user_input) but uses the rescue modifier (inline form) to assign 0 if an error occurs. Use the exact syntax: Integer(user_input) rescue 0.
Ruby
Need a hint?

Use Integer(user_input) rescue 0 to handle invalid input gracefully.

3
Try with a valid number string
Change the value of user_input to the string "123" exactly. Keep the number assignment the same using the rescue modifier.
Ruby
Need a hint?

Just replace the string value assigned to user_input with "123".

4
Print the result
Use puts to print the value of the variable number.
Ruby
Need a hint?

Use puts number to display the number.