Add #except to Array

Hi guys!

Time to time I meet questions on SO about how to take elements from array avoid some indexes.

I think it might be helpful for many developers to have something like Hash#except but for Array.

I would like to add PR with it if someone interested in it.

Thanks in advance for any thoughts about this idea.

Would this alias Array#excluding? I think the Array#except is natural and I’ve found myself asking why it’s not aliased already many times but I’m not the one to ask. :slightly_smiling_face:

It wouldn’t be alias :sweat_smile:

The main idea is to implement method which we can use to exclude elements from array by their indexes.

For example:
%w( a b c d e f).except(0, -1)

=> [‘b’, ‘c’, ‘d’, ‘e’]

Nice suggestion! :slight_smile:

I see how it would replicate the Hash#except syntax as seen here: https://apidock.com/rails/Hash/except

However, could this be confusing for those who don’t anticipate the index stripping behavior but more of a reject/excluding behavior?

i.e.:


%w( 1 5 6 8 0 9 0 ).except(0)

#=> [5,6,8,0,9,0]

Would it be better to explicitly add the index to the name such as #except_index or more verbose #except_with_index ?

I’m totally agree that it might be confusing so yeah, maybe #except_index will be the best variant :sweat_smile:

What would be a typical use case for such a function - I can understand the special case of wanting to remove the first / last items in the array, but an arbitrary one?

I think your question is kinda abstractive because many Rails/Ruby methods is mostly for special cases and many of them might be not used ever by most of the projects.

I think there should be a lot of use cases. It’s not gonna be the fastest method, but it will be quite popular. From my side I implemented such a method and used it for complex data parsing. I would recommend to add ranges to arguments.

I opened PR: https://github.com/rails/rails/pull/38611