Last Updated: July 26, 2022
·
49.14K
· nick-desteffen

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.

6 Responses
Add your response

So simple! I love it!

over 1 year ago ·

A little old but, it can get better using the Splat (asterisk):
class Array def except(*value) self - value end end

over 1 year ago ·

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.

over 1 year ago ·

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
```

over 1 year ago ·

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])

over 1 year ago ·