Question about capitalize! method


#1

Hello !

I’m on the exercice “Formatting with String Methods”.
https://www.codecademy.com/courses/learn-ruby/lessons/putting-the-form-in-formatter/exercises/formatting-with-string-methods?action=resume_content_item&link_content_target=interstitial_undefined

I don’t understand the difference between the two following codes :

print "What is your first name?"
first_name = gets.chomp
first_name.capitalize!
puts "Hello #{first_name} !"
print "What is your first name?"
first_name = gets.chomp.capitalize!
puts "Hello #{first_name} !"

For example, if the name entered by the user was ‘John’.
The first code displays ‘Hello John!"’.
The second code displays a blank “Hello !”.

I see on forum that capitalize! method return nil if no changes are made. Why is the name dispayed in the first code ?

Thank you for your help.


#2

gets.chomp is used to get user input

first_name = gets.chomp

assigns the user input to a var
and then you need to use

first_name.capitalize!

to use the string var you retrieved from user input and capitalize it

first_name = gets.chomp.capitalize!

doesnt get user input, it doesnt transform into a string, and you cant capitalize or format a method


#3

We find this very misleading and vague, and does not answer the question.

first_name = gets.chomp.capitalize!

works fine so long as the user does not capitalize their input. Otherwise it will not give the result we expect, but nil.

Try this code, for starters…

print "What's your first name? "
first_name = gets.chomp.capitalize
print "What's your last name? "
last_name = gets.chomp.capitalize
print "What city do you live in? "
city = gets.chomp.capitalize
print "What state? (xx) "
state = gets.chomp.upcase

puts "Your name is #{first_name.nil? ? 'nil' : first_name} #{last_name.nil? ? 'nil' : last_name} and you live in #{city.nil? ? 'nil' : city}, #{state.nil? ? 'nil' : state}."

Enter inputs that are already capitalized in your test.

What's your first name? Wee
What's your last name? Gillis
What city do you live in? Perth
What state? (xx) HD
Your name is Wee Gillis and you live in Perth, HD.

Now alter the code to this…

print "What's your first name? "
first_name = gets.chomp.capitalize!
print "What's your last name? "
last_name = gets.chomp.capitalize!
print "What city do you live in? "
city = gets.chomp.capitalize!
print "What state? (xx) "
state = gets.chomp.upcase!

puts "Your name is #{first_name.nil? ? 'nil' : first_name} #{last_name.nil? ? 'nil' : last_name} and you live in #{city.nil? ? 'nil' : city}, #{state.nil? ? 'nil' : state}."
What's your first name? Wee
What's your last name? Gillis
What city do you live in? Perth
What state? (xx) HD
Your name is nil nil and you live in nil, nil.

#4

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