Expand All

Input And Output

Goals

  • Print to the screen with puts

  • Read user input with gets

Step 1

Type this in irb:
puts 'Hello World'

puts (put string) is a way of printing information to the user of your program.

Take some time to contemplate the output of puts in irb:

Expected result:
irb :006 > puts 'Hello World'
Hello World
 => nil
irb :007 >

The method puts always has the return value of nil, which is what we see after the => in the output. Printing 'Hello World' to the screen is just a side-effect.

Step 2

print is like puts but doesn't make a new line after printing.

Create a new file called input_and_output.rb

Type this in the file input_and_output.rb:
print "All"
print " "
print "in"
print " "
print "a"
print " "
print "row"

Save the file and exit out of irb.

Type this in the terminal:
ruby input_and_output.rb

Step 3

Create a new file called conditionals_test.rb

Type this in the file conditionals_test.rb:
print "How many apples do you have? > "
apple_count = gets.to_i
puts "You have #{apple_count} apples."

Save the file and exit out of irb.

Type this in the terminal:
ruby conditionals_test.rb

When prompted, type in a number of apples and press enter.

print is like puts but doesn't make a new line after printing.

gets, or get string, pauses your program and waits for the user to type something and hit the enter key. It then returns the value back to your program and continues execution. Since the user could have typed anything ('banana', '19.2', '<<!!@@') we use to_i to ensure what comes out is an integer. If the user didn't type a valid integer, to_i returns 0.

Challenge(s)

Create a program that echoes (or repeats) user input. Use puts and gets to make this program work.

Here is a sample of how the program might run. The > has been used below to indicate that the user should input the value proceeding it.

What do you want to say?
> sally sells seashells
You said: sally sells seashells

Next Step:

Back to Numbers And Arithmetic