Section 7.4. Determining the Date of Easter


7.3. Determining the Day of the Week

There are several ways to determine the day of the week. First, the instance method to_a returns an array of time information. You can access the seventh element, which is a number from 0 to 6 (0 meaning Sunday and 6 meaning Saturday).

time = Time.now day = time.to_a[6]            # 2 (meaning Tuesday)


It's better to use the instance method wday as shown here:

day = time.wday               # 2 (meaning Tuesday)


But both these techniques are a little cumbersome. Sometimes we want the value coded as a number, but more often we don't. To get the actual name of the weekday as a string, we can use the strftime method. This name will be familiar to C programmers. There are nearly two dozen different specifiers that it recognizes, enabling us to format dates and times more or less as we want. (See section 7.21, "Formatting and Printing Date/Time Values.")

day = time.strftime("%a")     # "Tuesday"


It's also possible to obtain an abbreviated name.

long  = time.strftime("%A")   # "Tuesday"





The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net