Help with capitalization error? Thank You


#1


There is no error in regards to the code executing, however, I have noticed if I answer any of my questions starting with capitalization at the start of the word e.g "what is your first name?" John, the code executes, but shows a blank answer for this input when printing. But if i answer the same question with john (all in lowercase) the input prints out correctly and capitalizes the first letter of the first name given.

How can i fix this?

Thank you!!


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 are you from?"
city = gets.chomp .capitalize!
print "What state are you from?"
state = gets.chomp .upcase!   
puts "Your name is #{first_name} #{last_name} and you are from the city of #{city} in the state of #{state}"


#2

Read what capitalize! and upcase! do
https://ruby-doc.org/core-2.2.0/String.html


#3

Hey, thanks for the link, do you mean this part?

"capitalize! → str or nil
Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil if no changes are made. Note: case conversion is effective only in ASCII region."

the part that says returns nil if no changes are made??? i don't get a response of nil, it literally shows a blank space.

quite confused, relatively new to programming, excuse my ignorance :slight_smile:

Thank you for any help/guidance


#4

Yes, that part. And also, and much more impartantly, that you should find such descriptions whenever you use something to see what behaviour it has and what promises it makes. You might think it's crazy to look up so many things, but the real crazy is in not doing so because then it's just guessing.

If you're not convinced that the value is nil, then print it (though do note that it may convert to string as something you won't see, such as empty string, so you may want to compare the value to nil instead to see if it's equal.

nil's to_s method returns an empty string:
https://ruby-doc.org/core-2.2.0/NilClass.html#method-i-to_s
(again, you'd just look it up)

puts nil.nil?

output:

true

#5

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