Saturday, October 18, 2008

Ruby: Time made easy

Here's another example of how Ruby just makes things simple. Imagine you're working with time and you have to figure out the difference between 2 times and whether they fall within a certain range. In most languages, you have to figure out how many seconds exist in your time range. For example, 1 minute would have 60 seconds and 1 day would have 86,400 seconds. That's not too hard to figure out, but imagine the readability!

t2 - t1 < 86400

That just begs the question, "Where does 86400 come from?". Imagine you had to explicitly put down the number for 1 week?

Well, Ruby is awesome in that it concentrates on readability. Since everything in Ruby is an object, numbers are just Fixnum (or Bignum). Either way, that means we can use certain methods associated with the object. Check this out:

t2 - t1 < 1.second
t2 - t1 < 1.minute
t2 - t1 < 1.hour
t2 - t1 < 1.day
t2 - t1 < 1.week
t2 - t1 < 1.month
t2 - t1 < 1.year

Now how readable is that?


W

No comments: