Getting Input


Collapse Content

So far, the Product program used hard-coded code to create and show products from the 'database'. In this challenge, let's turn it into an actual program that can be used by anyone with access to a command line.

Getting Input

Standard I/O
When you use print or puts in Ruby, it prints text to Standard Output. This is text that is usually shown on a command line or terminal. Standard Input is text that is entered on the terminal that your program can use. It is also the input that is passed in to many of the coding challenges on this site.

gets
It's really simple to get input in Ruby. You just use a method: gets, which gets a line of input. For example if put this code in a file called greet.rb

puts "Your name?"
name = gets
puts name

You can then run the program from the command line by entering ruby greet.rb in its directory. The program will then run, and let you enter your name:

$ ruby greet.rb
Your name?
Jim
Hello Jim 

strip
You can use standard string methods to cleanup given input. For example, use strip to strip off all whitespace from the beginning and end of the input.

puts "Your name?"
name = gets.strip
puts name

Challenge

Create a class that gets all the input and passes it to your controller, one line at a time.

There are 2 kinds of input, for creating and showing products:

input format sample input sample output action taken
create Name description
create Cow moos
Product created
(Creates product and adds to database.)
show index 
show 0
Cow moos
Retrieves product from index 0 and prints it

Here are some step-by-step directions you can follow:

  1. Create a class, which you can call Router. Create an instance of your controller class inside it.
  2. Inside the class, create a single method with a loop. You can use a while loop or a simple variant of it:
    loop do 
      # do stuff
      break if some_condition
    end
  3. (This code will loop until some_condition is reached, when it will break out of the loop.)
  4. Inside the loop, get the input, strip it, and assign it to a variable.
  5. If the input consists of "quit", break out of the loop.
  6. Otherwise, call your controller method process, and pass it the input.
  7. Below your router class, start your router and call it's method to go through the input.

When you're finished, you'll have a complete program! Next, you can optionally learn how to use inheritance to improve it.

Challenge

Create a program that creates or shows a product for each line of input.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]