Use Ruby and Relax

Posted by Jim Jagielski on Thursday, September 15. 2005

Talk about your 180's. RoR has really gotten me into the joy of Ruby, even without using Rails. It's hard to get used to the "everything is an object" idea, because we're so used to all the caveats other languages have. But once you learn to trust Ruby, things just flow. And Mixins just make it all better. For example, on some apps, I needed to be able to skip selections within an Array ("grab every 3 elements"). The below little hack makes that super easy to implement, and use those methods naturally and natively.
class Array   def each_x(x)     (0 .. (length.to_f/x).ceil - 1).collect { |i| yield(self[i*x]) }   end   def every(x)     each_x(x) { |i| i }   end   def collect_x(x)     each_x(x) { |i| yield(i) }   end end

1 Comment for this entry

Display comments as Linear | Threaded

  • Tom Copeland
    Yup, right on. Devin Mullins suggested a great way to explain core class modification to Java programmers. Just ask, "do you have a StringUtils 'class' with a bunch of static methods?". Of course, everyone does. So then you explain how you can just attach those methods to String and use them whereever. Sometimes you get an "ahh, ok, I see" moment out of that.

The author does not allow comments to this entry

Quicksearch

Search for an entry in IMO:

Did not find what you were looking for? Post a comment for an entry or contact us via email!