skzsoa
Last Updated: October 28, 2016
·
13.16K
· nick-desteffen
Img 2817

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.

Say Thanks
Respond

5 Responses
Add your response

16275
10a836ff08ac1d4082339e6cde68a084

So simple! I love it!

over 1 year ago ·
17325
4cee47c73fffb5b662c547eaf2670726

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
9642e8bd2c0a4aa406f0d856cde7a6f2
over 1 year ago ·
22164
Cfd59846a3f2c8a93a714a75e5eeff3f

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 ·