Ruby Array.except
Sometimes you need an array, except you need 1 object removed for whatever reason. Normally I'd write:
users = [user1, user2, user3, user4, myself]
users.reject{|u| u == myself}.each do |user|
user.some_method
end
That was pretty ugly. Meet array.except
class Array
def except(value)
self - [value]
end
end
We can now do:
users.except(myself).each do |user|
user.some_method
end
Looks good, reads well, simple to do.
Written by Nick DeSteffen
Related protips
6 Responses
So simple! I love it!
A little old but, it can get better using the Splat (asterisk):
class Array
def except(*value)
self - value
end
end
They added a similar method in the next release of active support:
https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/array/access.rb#L38
Why to add a method for anything as simple as this?
[1,2,3]-[1]
BTW open classes suck because you have to haul your methods everywhere.
I add except! like Rails Hash#except
```ruby
class Array
def except(values)
dup.except!(values)
end
def except!(*values)
values.each {|v| delete(v)}
self
end
end
```
Nice snippet! I made a slight change to accept single or array parameters:
class Array
def except(value)
self - [value].flatten
end
end
So now it works for single
[1,2,3].exclude(2)
And also works for multiple
[1,2,3].exclude([1,3])