Saturday, April 2, 2011

2nd Success, Do you leap? pt.6

It's amazing when things suddenly fall into place. So after finding how leap years are a fantastic application of the modulo operation in Ruby, I wanted to make it a .method? operation. This is the one where you go 1352.leap? and it returns true if true and false if false. The first clue on how to make the program work this way came when I read on why's poignant guide to ruby that you can define Ruby classes like string and it simply adds on your method to the present class.

So the first thing I needed to do was find what class are integers. I thought it might be int, but when I started the irb session and wrote 1532.class it returned Fixnum. Cool, so now the first half was in place.

The second part would be how to get it to operate on the number previous the period-method call so I didn't have to put the number as a method argument in parenthesis like the first leap-year program. And here is where the magic happened.

I tried a few things and then suddenly I remembered seeing a lot of examples with "self." Now I didn't know what self was or have gotten to it in the book, but it fit. So I tried it on irb and success! It just fell into place and I code the program to work how I wanted.

Now if only I was having this much luck with the unicode one program...

Quick note: I've put the programs up on my website so you can download them if you want and see the code. Find them here.

No comments:

Post a Comment