puts and gets
You've seen that before:
puts "Hello world"
putswith any expression:
puts a_number
puts 12.0 / 4
puts 12.0 / 4
What does Ruby do?
12.0 / 4)
3.0on the command line
getsallows the user to interact with your program
puts
Save this code in a file called
gets.rb:
puts "Hi! What's your name?"
name = gets.chomp
puts "Aha! Your name is: " + name
In the command line, execute the code by running
ruby gets.rb
$ ruby gets.rb Hi! What's your name? Ferdinand Aha! Your name is: Ferdinand
puts "Hi! What's your name?"
name = gets.chomp
puts "Aha! Your name is: " + name
getsis executed, the Ruby program stops
It only continues when the user types Enter
nameas a string
gets.rblike this:
puts "Hi! Please enter a number:"
number = gets.chomp
puts "Here's double that number: " + (2 * number)
And run the code!
gets.rb:3:in `*': String can't be coerced into Integer (TypeError)
numbercontains a string, because
gets.chompalways returns a string!
to_ito convert from string to integer:
puts "Hi! Please enter a number:"
number = gets.chomp
puts "Here's double that number: " + (2 * number.to_i)
Run the code!
gets.rb:3:in `+': no implicit conversion of Integer into String (TypeError)
to_sto convert from integer to string:
puts "Hi! Please enter a number:"
number = gets.chomp
puts "Here's double that number: " + (2 * number.to_i).to_s
Run the code!
$ ruby gets.rb Hi! Please enter a number: 43 Here's double that number: 86
What questions do you have?