der kl@mmeraffe | ruby. java. development.

a developers guide to the world of code

Tuesday, August 08, 2006

Rails: All those little things

Image you've got a List (or an Array or whatever you like to call it) with objects. Those are articles with lots of fields. And you want to sort this List by one of its fields.
One thing some love (or hate) bout ruby is its use of blocks. Some say they are the most powerful thing imaginable, some say doing 2.times {p blub} isn't that cool (maybe they are both wrong and right).
Whatever. To sort a List is not a nice task in lots of programming languages. But look at this:

articles.sort! do |a, b|
a.value <=> b.value
end

Got it? You tell the List to sort itself (by calling the sort-method and putting a block in it). The block uses a funny operator that return -1, 0 or 1, depending on which element is bigger. The method uses this information to sort the List.

Those are the little things why i really like to code in ruby (with or without rails)

add to del.icio.us | submit to digg | submit to reddit

1 Comments:

  • At 2:15 PM, Anonymous Anonymous said…

    This is very interesting site...
    » » »

     

Post a Comment

Links to this post:

Create a Link

<< Home