Get items of an array that match a condition
Author |
Message |
DtY
![](http://compsci.ca/v3/uploads/user_avatars/8576159234be48b7a8b0e8.png)
|
Posted: 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 |
|
|
|
|
![](images/spacer.gif) |
Sponsor Sponsor
![Sponsor Sponsor](templates/subSilver/images/ranks/stars_rank5.gif)
|
|
![](images/spacer.gif) |
DtY
![](http://compsci.ca/v3/uploads/user_avatars/8576159234be48b7a8b0e8.png)
|
Posted: 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 |
|
|
|
|
![](images/spacer.gif) |
Vermette
![](http://compsci.ca/v3/uploads/user_avatars/637825944810b5d4444c6.jpg)
|
|
|
|
![](images/spacer.gif) |
wtd
|
Posted: 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 |
|
|
|
|
|
![](images/spacer.gif) |
gianni
![](http://compsci.ca/v3/uploads/user_avatars/2828365714b5bd9cc211e8.png)
|
Posted: 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?) |
|
|
|
|
|
![](images/spacer.gif) |
|
|