Chapter 7 - Hashes

Exercise 1: Convert months

Below is an english_date method that takes an ISO date (a standardized format with the year, month, and day, in that order) and converts it to plain English, with the name of the month spelled out. So, “2007-02-24” would be converted to “February 24, 2007”.

But the method is incomplete; the month_names variable needs to be set to a hash with the month numbers as keys, and the month names as values. Once that’s done, it should be able to convert the months successfully.

def english_date(iso_date)
  # To make the code below work, define a
  # month_names hash with "01" through "12"
  # as keys, and "January" through "December"
  # as values.
  date_parts = iso_date.split("-")
  year = date_parts[0]
  month = date_parts[1]
  day = date_parts[2]
  "#{month_names[month]} #{day}, #{year}"

# Should print "June 20, 2002"
puts english_date("2002-06-20")
# Should print "December 13, 1974"
puts english_date("1974-12-13")

When you’re ready, have a look at the solution.

Exercise 2: IRB Session

Launch irb from your terminal, and try the following expressions:

> my_string = "ruby is so cool"
> my_string.methods
> my_string.reverse.upcase
> my_string.insert(11, "very, very ")
> "Rolling a die... we got #{ rand(1..6) }"
> "There are #{ 60 * 60 } seconds in an hour."
> 42.to_s
> "42".to_i

After you try them out, you can see an explanation of the results.