Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Get items of an array that match a condition
Index -> Programming, Ruby -> Ruby Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
DtY




PostPosted: Mon Oct 12, 2009 3:24 pm   Post subject: 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 [].methods, but couldn't find anything that looked right.
What I want is the method that will give me this:
Ruby:
> [1,2,3,4,5,6,7,8,9,10].someMethod{|n| n%2 == 0}
[2,4,6,8,10]


Thanks
Sponsor
Sponsor
Sponsor
sponsor
DtY




PostPosted: Mon Oct 12, 2009 3:35 pm   Post subject: RE:Get items of an array that match a condition

Found it, it's Array#select
Vermette




PostPosted: Mon Oct 12, 2009 3:36 pm   Post subject: RE:Get items of an array that match a condition

select:
http://www.ruby-doc.org/core/classes/Array.html

edit: beaten
wtd




PostPosted: Wed Oct 14, 2009 10:23 pm   Post subject: RE:Get items of an array that match a condition

Ruby:
class FixNum
    def even?
        self % 2 == 0
    end
end

module Enumerable
    def all_evens
        select { |x| x.even? }
    end
end
gianni




PostPosted: Thu Oct 15, 2009 3:33 pm   Post subject: Re: RE:Get items of an array that match a condition

wtd @ Wed Oct 14, 2009 10:23 pm wrote:
Ruby:
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:

Ruby:
class FixNum
    def even?
        self % 2 == 0
    end
end

array.select(&:even?)
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 5 Posts ]
Jump to:   


Style:  
Search: