Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Let's use the new method we found in the String class documentation to fix our widget store program's output.
If we try to run the widget store program as it is now, the gets
method returns the string the user types with a newline character on the end. This messes up the output when we try to print it. But when we looked at the documentation for the String
class, we learned that strings have a method named chomp
that can remove newline characters from the end of the string.
- Chain a call to
chomp
onto the return value of the gets method.
def ask(question)
print question + " "
gets.chomp # Add ".chomp" here
end
puts "Welcome to the widget store!"
answer = ask("How many widgets are you ordering?")
puts "You entered #{answer} widgets"
Output:
Welcome to the widget store!
How many widgets are you ordering? 10
You entered 10 widgets
- In
ask
method, keyboard input is returned fromgets
, with a newline character on the end - We chained a method call to
chomp
after the call togets
, sochomp
gets called on the return value ofgets
. -
chomp
returns a new string with the newline character removed. - That's what gets returned from the
ask
method, stored in theanswer
variable, and then displayed on the terminal.
Additional practice
We've created a workshop where you can get additional practice calling methods on Ruby objects. Don't miss this chance to strengthen your skills!
Visit the workshop here: Practice Input and Output in Ruby
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up