Computers have many senses -- keyboard, mouse, network card, digital camera, etc. Collectively, these are called INPUT.
Computers can also express themselves in many ways -- text, graphics, sound, network, printers, etc. Collectively, these are called OUTPUT.
Input and Output together are called I/O.
In Ruby,
puts
means "print a line to the terminal"gets
means "read a line from the terminal"gets
reads all the characters from the keyboard and puts them into a new string, until you press RETURN
hello.rb
in your text editorChange it to contain the following code:
puts "What is your name?"
name = gets
puts "Hello, " + name + "!"
Save the file and switch back to the terminal
Run the program using ruby hello.rb
Type in your name and press the Return key (also called Enter)
What happens? Is this what you expected?
Uh-oh! We've got trouble... what is that exclamation point doing way down there?
The first thing to do is DON'T PANIC!
You are totally going to figure this out.
And even if you don't, you haven't actually broken anything.
In fact, it's really hard to break a computer, so just stay calm.
gets
, Ruby reads all the characters, including the newline!strip
to a string, it will remove all SPACES and NEWLINES from both endsChange the program to look like this:
puts "What is your name?"
name = gets.strip
puts "Hello, " + name + "!"
name.rb
that asks two things:
ruby name.rb
on the command line.You just wrote a program!
You are now officially a coder. HIGH FIVE!
name.rb
so it also prints the number of characters in the user's name.For instance:
What is your first name?
Alex
What is your last name?
Chaffee
Hello, Alex Chaffee!
Your name is 11 characters long.
/