skzsoa
Last Updated: May 22, 2019
·
26.51K
· 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

16275

So simple! I love it!

over 1 year ago ·
17325

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 ·
19831
over 1 year ago ·
22164

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 ·
28274

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 ·
31016

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

7 months ago ·