views:

211

answers:

2

Hi All,

A common idiom that my camp uses in rails is as follows:

def right_things(all_things, value)
    things = []
    for thing in all_things
       things << thing if thing.attribute == value
    end
    return things
end

how can I make this better/faster/stronger?

thx

-C

+9  A: 
def right_things(all_things, value)
    all_things.select{|x| x.attribute == value}
end
Chris Doggett
+1  A: 

If your things are ActiveRecord models and you only need the items selected for your current purpose, you may, if you're using Rails 2.0 (? definitely 2.1) or above, find named_scopes useful.

class Thing
  named_scope :rightness, lambda { |value| :conditions => ['attribute = ?', value] }
end

So you can say

Thing.rightness(123)

, which is (in this case) similar to

Thing.find_by_attribute(123)

in that it boils down to a SQL query, but it's more easily chainable to modify the SQL. If that's useful to you, which it may not be, of course...

Mike Woodhouse