4

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

2 Answers 2

13
def right_things(all_things, value)
    all_things.select{|x| x.attribute == value}
end
Sign up to request clarification or add additional context in comments.

Comments

1

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...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.