a. Create a new program named
date.rb. Copy or type in something like the “Hello, World” program and make sure you can run it. Let the program say “Hello, date” to ensure you are running the correct program.
b. Following the example in Section 2.5, write a program that creates variables named
day will contain the day of the week and
date will contain the day of the month. Assign values to those variables that represent today’s date. What type is each value?
c. Print (
puts) the value of each variable on a line by itself. This is an intermediate step that is useful for checking that everything is working so far.
d. Modify the program so that it prints the date in standard American format:
Friday, May 12, 2006
e. Modify the program again so that the total output is:
American format: Friday, May 12, 2006 European format: Friday 12 May, 2006
The point of this exercise is to use print statements or string interpolation to display values with different types (
String), and to practice developing programs gradually by adding a few statements at a time.
a. Create a new program called time.rb. From now on, I won't remind you to start with a small, working program, but you should.
b. Following the example in Section 2.8, create variables named
second, and assign them values that are roughly the current time. Use a 24-hour clock, so that at 2 p.m. the value of hour is 14.
c. Make the program calculate and print the number of seconds since midnight.
d. Make the program calculate and print the number of seconds remaining in the day.
e. Make the program calculate and print the percentage of the day that has passed.
f. Change the values of
second to reflect the current time (I assume that some time has elapsed), and check to make sure that the program works correctly with different values.
The point of this exercise is to use some of the arithmetic operations, and to start thinking about compound entities, such as the time of day, which are represented with multiple values. Also, you might run into problems computing percentages with
Integers, which is the motivation for floating-point numbers in the next chapter.
HINT: You may want to use additional variables to hold values temporarily during the computation. Variables like this, that are used in a computation but never printed, are sometimes called intermediate or temporary variables.