Second Ruby Exercises
Your second ruby exercises
Basic Methods
Multiply (Easy)
Write a method that you can multiple two numbers (x,y). Test with the following examples:
- 4, 2
- 0, 4
- 900, 32
- 29999, 0
Divide (Easy, with a special case)
Write a method that you can divide two numbers (x,y). If the denominator is zero, set it to the numerator (so that the method returns one). Test with the following examples:
- 4, 2
- 0, 4
- 900, 32
Print Name
Write a method that takes a parameter (name) and greets that user.
Smallest Number
Write a method that evaluates two numbers and returns the smallest. If the numbers are the same, it should return a message stating so.
String Reverse
Write a method that accepts a string and returns the characters in reverses order.
Hint: Look at the Ruby documentation.
Loops
While Loop
Write a method that uses a while
loop to count from 1 to 1000 and print the
number of the current iteration to the screen. (That is, the first time
through, the loop should print “1”; “2” the next time through; and so forth.)
Until Loop
Write a method that uses an until
loop to print each number from 0 to 5.
For Loop
Write a method that uses a for
loop to print each number from 1 to 10.
Times Loop
Write a method that uses a times
loop to print each number from 0 to 10.
Classes
Write a simple class that defines a person with attributes of
first_name
, last_name
and has a method signature of to_s
which
prints the object as “Jefferson, Thomas”.
Can’t Get Enough?
Can’t get enough? Work through the Learn Ruby the Hard Way exercises and/or implement the last programming exercises as Objects.