431 views
What's the return value of the following Ruby 3 code?
str = "hello\n" str.chomp!.reverse # => "olleh" str = "hello" str.chomp!.reverse # => ???
The correct answer is
nil
It raises NoMethodError
"olleh"
"hello"
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
In Ruby, the String#chomp!
method is used to remove the record separator (typically a newline) from the end of a string, modifying the string in place.
If the method makes no modifications (because the string does not end with a record separator), it returns nil
instead of the modified string.
This behavior can lead to unexpected issues, especially when chaining methods.
Consider the following code:
str = "hello" str.chomp!.reverse # Raises NoMethodError: undefined method `reverse' for nil:NilClass
In this example:
- The string str
does not end with a newline character, so str.chomp!
makes no modifications and returns nil
.
- The subsequent call to reverse
is attempted on nil
, which raises a NoMethodError
because nil
does not have a reverse
method.
To avoid this issue, you can use a conditional check or use the non-destructive String#chomp
method, which always returns a new string and does not modify the original.
str = "hello" result = str.chomp! result = str if result.nil? result = result.reverse puts result # => "olleh"
String#chomp
str = "hello" result = str.chomp.reverse puts result # => "olleh"
By using String#chomp
instead of String#chomp!
, you avoid the potential issue of nil
being returned, ensuring that the subsequent method calls operate on a valid string object.
Voilà!
Our latest course, Advanced Ruby, is now available! It includes 20 modules and over 90 questions.
Subscribe to RubyCademy for just $6.50 per month to access our courses, over 200 resources, and enjoy two new additions every week. 🤩
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©