Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Ruby Basics!
You have completed Ruby Basics!
If you try to treat a string like a number, you may get strange results. Let's learn how to convert strings that contain a number to actual numbers.
- If you use the
*
operator on a string, it repeats the string the number of times you supply. - That can give you strange results if you try to treat a string containing a number as if it was an actual number.
puts "A" * 10 # AAAAAAAAAA
puts "7" * 10 # 7777777777
- We need to use one of these methods to convert the string to an actual number before multiplying it.
puts "7".to_i * 10 # 70
Widget store
Let's use the to_i
method to convert the string the user entered to an actual number, then multiply the result:
def ask(question)
print question + " "
gets.chomp
end
puts "Welcome to the widget store!"
answer = ask("How many widgets are you ordering?")
number = answer.to_i
puts "For #{number} widgets, your total is: $#{number * 10}"
Output:
Welcome to the widget store!
How many widgets are you ordering? 7
For 7 widgets, your total is: $70
Additional practice
We've created a workshop where you can get additional practice working with numbers in Ruby. Don't miss this chance to strengthen your skills!
Visit the workshop here: Practice Ruby Numeric Types
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