Ruby Monstas


puts and gets

puts

You've seen that before:

puts "Hello world"
But we can use
puts
with any expression:
puts a_number
puts 12.0 / 4

puts

puts 12.0 / 4

What does Ruby do?

  1. Evaluates the expression (
    12.0 / 4
    )
  2. Outputs
    3.0
    on the command line

gets

gets
allows the user to interact with your program

It's the "opposite" of
puts

gets

Save this code in a file called

gets.rb
:

puts "Hi! What's your name?"
name = gets.chomp
puts "Aha! Your name is: " + name

gets

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

gets

puts "Hi! What's your name?"
name = gets.chomp
puts "Aha! Your name is: " + name
As soon as
gets
is executed, the Ruby program stops

It only continues when the user types Enter

The characters the user entered are stored in the variable
name
as a string

gets

Change
gets.rb
like 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)
number
contains a string, because
gets.chomp
always returns a string!

gets

We can fix it by using
to_i
to 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)
Ruby doesn't allow us to add a number to a string

gets

We can fix it by using
to_s
to 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?