Tuesday, November 8, 2011

Exercise 11: Asking Questions: Learn Ruby The Hard Way: Practicum

So far we've been doing a lot of printing, and that's been a one way street. Programs aren't terribly interesting that way, they need to have input to typically do anything useful. In these early stages, that means we will be looking at physically feeding input from a prompt (later I'm sure we'll deal with file input or other means of geting input into the program).

So let's feed some input to the program, shall we?

print "How old are you? "
age = gets.chomp()
print "How tall are you? "
height = gets.chomp()
print "How much do you weigh? "
weight = gets.chomp()

puts "So, you're #{age} old, #{height} tall and #{weight} heavy."

[and here it is]

In this case we use "print" instead of "puts". print doesn't add a new line automatically, so the answer to the question appears on the same line. puts  automatically adds a new line.

What You Should See

$ ruby ex11.rb
How old are you? 35
How tall are you? 6'2"
How much do you weigh?  180lbs
So, you're '35' old, '6'2"' tall and '180lbs' heavy.

[Well, I'm a little older and weigh a little more than Zed does, but other than that, yep :) ]

Extra Credit

Go online and find out what Rubys gets and chomp methods do.

[gets allows the user to enter a string value directly to input. chomp removes the newline from the end of the line. gets.chomp() means that whatever is entered stores that variable name only, not the newline. Also, chomp can be applied to any variable, see below]

Can you find other ways to use gets.chomp? Try some of the samples you find.

[see below]

Write another "form" like this to ask some other questions.


We'll be dealing with this stuff in a little while, but gets is an object and chomp is an object method. Notice that we used chomp both with gets, as in gets.chomp, but we also used it with an other variable, which is "name". We assigned name with a value by using gets, and then modified name by using name.chomp, or put more simply, name without the newline at the end.

1 comment:

Anonymous said...

very helpful site as I worth through this book :)