Archive | August, 2007

22 August 2007 ~ 0 Comments

Determining the number of days in a month

Here is a simple method that returns number of days for wanted month and year. If year is ommited current year is selected. def month_days(month, year=Date.today.year) mdays = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] mdays[2] = 29 if Date.leap?(year)mdays[month] end Simple examples: month_days(1) => 31 month_days(2, 2007) => [...]

Continue Reading

03 August 2007 ~ 9 Comments

Ruby Inject

You probably frequently have to iterate through a list and accumulate a result that changes as you iterate. Let’s take the following array: nums = [1, 3, 5, 7] If you want to find a sum of all the items in the array, you could write something like this: sum = 0 nums.each { |n| [...]

Continue Reading