Ruby beginner

What’s more proper out of these two codes and why or are they equally valid?

print "give me something: "
user_input = gets.chomp
user_input.downcase!

or

print "give me something: "
user_input = gets.chomp.downcase!

Thanks. C

No, the two aren’t equivalent. The first code is better.

When the user input has at least one uppercase letter, then both codes will give the same result. For Example, if the user inputs a string like “ABCD” or “abCd”, then both codes will give the same result i.e. “abcd”. This can be verified by adding the statement puts user_input at the end of each code.

The problem comes when the user input is completely lowercase already. Suppose the user input is “abcd”. The first code will store this string in user_input. In the next statement, it will apply the downcase method. Since the string is already lowercase, so nothing will happen. When we puts user_input, we will see the original string “abcd” as expected.

In the second code, there are a number of things happening in the same statement. Suppose the user input is “abcd”. The downcase method is applied to the user input and the result is stored in user_input. The problem is that the downcase! method

Downcases the contents of str , returning nil if no changes were made.
Documentation: Class: String (Ruby 3.1.2)

Since “abcd” is already lowercase, so nil is returned. If you puts user_input, you will see nothing being printed on screen.

However, if you omit the bang (!), then the second code will give same result as the first code.

# Code 1:
print "give me something: "
user_input = gets.chomp  # user enters "abcd"
user_input.downcase!
puts user_input # "abcd" is printed

# Code 2:
print "give me something: "
user_input = gets.chomp.downcase! # user enters "abcd"
puts user_input # Nothing is printed

# Code 3 (Code 2 edited):
print "give me something: "
user_input = gets.chomp.downcase # user enters "abcd"
puts user_input # "abcd" is printed

Interesting. Thank you for your time.

C

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.