4.4 Thith Meanth War: Setting up the "if" branch P1: .downcase vs .downcase!


#1



Exercise: Thith Meanth War! | Setting Up the 'If' Branch, Part 1

Context:

Hi, the following code works even if the user inputs a string that is already all lowercase:

print "Thome input pleathe."
user_input = gets.chomp
user_input.downcase!
print "We got an s!!" if user_input.include? "s"

I was tempted to try:

user_input = gets.chomp.downcase!

But this results in error if the user inputs a string that is already all lowercase, because .downcase! returns nil for such input, and assigns nil to user_input, causing an error at the if statement. This I understand.

So my question is why codeacademy insists on using .downcase!, when the following could work:

user_input = gets.chomp.downcase

Question: Here is my guess, can someone please tell me if I am right?

My guess is that because .downcase! modifies in-place,

user_input = gets.chomp
user_input.downcase!

saves on memory, whereas

user_input = gets.chomp.downcase

while more elegant, wastes memory by creating a copy of the string, which is modified by .downcase, and then assigned to user_input. Is this correct? Thanks in advance...


#2

Uses memory, I"ll go with. Wastes memory only applies to naive solutons that don't validate user inputs before applying class based methods.

We could for instance jerry-rig the program to always have an uppercase letter before applying downcase!, then remove it afterward. Of course this would take some work. If we thought we could simply toss a bone to this one, we were wrong.

 > user_input = ((gets.chomp + "Z").downcase!)[-2]
 
=> nil
 > user_input = ((gets.chomp + "Z").downcase!)[-2]
 a
=> 97
 > user_input
=> 97
 > user_input = ((gets.chomp + "Z").downcase!)[-2]
 Z
=> 122
 > user_input = ((gets.chomp + "Z").downcase!)[-2]
 surprise
=> 101
 > user_input = ((gets.chomp + "Z").downcase!)[-1]
 surprise
=> 122
 > "surprise"[-2].chr
=> "s"

#3

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