
-----------------------------------
DtY
Mon Oct 12, 2009 3:24 pm

Get items of an array that match a condition
-----------------------------------
I feel stupid asking this.. I should know the answer, but I just can't remember what method I want. I looked at > 

Thanks

-----------------------------------
DtY
Mon Oct 12, 2009 3:35 pm

RE:Get items of an array that match a condition
-----------------------------------
Found it, it's Array#select

-----------------------------------
Vermette
Mon Oct 12, 2009 3:36 pm

RE:Get items of an array that match a condition
-----------------------------------
select:
http://www.ruby-doc.org/core/classes/Array.html

edit: beaten

-----------------------------------
wtd
Wed Oct 14, 2009 10:23 pm

RE:Get items of an array that match a condition
-----------------------------------
class FixNum
    def even?
        self % 2 == 0
    end
end

module Enumerable
    def all_evens
        select { |x| x.even? }
    end
end

-----------------------------------
gianni
Thu Oct 15, 2009 3:33 pm

Re: RE:Get items of an array that match a condition
-----------------------------------
class FixNum
    def even?
        self % 2 == 0
    end
end

module Enumerable
    def all_evens
        select { |x| x.even? }
    end
end

Building on wtd's example, if you're using Rails or Ruby 1.9:

class FixNum
    def even?
        self % 2 == 0
    end
end

array.select(&:even?)
