Here is a slightly more Rubyish way to write this:
class Date
def weekdays
current = Date.new(year, month, 01)
result = []
while current.month == month
result << current if (1..5) === current.wday
current += 1
end
result
end
end
Now if you have a Date you can just call weekdays on it. I've taken out a
few unneeded parenthesis, but leaving them in wouldn't necessarily be an
unRuby way to write. Also the wday comparision now uses a Range and the
=== operator. This could also be written (1..5).member?(current.wday). In
addition I've decided to use << instead of push, and have also used the
syntax which puts the if at the end of the line (I'm not sure what the
official name is.) Lastly, there is no need for return if what you are
returning is the last line in the method.
Ryan Leavengood
mattscape wrote:
> Hi everyone
>
> I am playing around with ruby. And as a Java developer I wrote this
> method to get me the weekdays of a month:
> ########
> def weekdays(month)
> current = Date.new(month.year,month.month,01)
> result = Array.new
> while (current.month == month.month)
> if(current.wday != 0 && current.wday != 6)
> result.push(current)
> end
> current += 1
> end
> return result
> end
> ########
>
> What would be a nice ruby way to write this?