select!
Posted by jacqui maher on April 11, 2008 at 01:55 PM
I found myself having to reverse logic in some code I wrote recently due to the wants of the client doing a 180. I had been using reject! to remove elements in an array, and realized that I now wanted to use select! - only there is no select!
I started to write:
arr = arr.select{|a| some.method.here }
when it occured to me that was a little clunky. I wanted select in place.
Here’s my version of it:
1 class Array
2 def select!(&block)
3 selected = self.select(&block)
4 if selected.size > 0
5 replace(selected)
6 else
7 nil
8 end
9 end
10 end
Usage:
1 >> arr = ["Ren", "Easy-E", "Ice Cube", "DJ Yella", "Dr Dre"]
2 # => ["Ren", "Easy-E", "Ice Cube", "DJ Yella", "Dr Dre"]
3
4 >> arr.select!{|a| a =~ /^D/ }
5 # => ["DJ Yella", "Dr Dre"]
6
7 >> arr.select!{|a| a =~ /^J/ }
8 # => nil
9
10 >> arr
11 # => ["DJ Yella", "Dr Dre"]
Comments
There are 2 comments on this post. Post yours →
Any reason you didn’t just change
arr.reject!{|e| e.some_method}
to
arr.reject!{|e| !e.some_method}
Sure, you could do that, but I was trying to avoid the double negative. You know, for readability’s sake :)
Post a comment
Required fields in bold.