I was not able to find any reference on the webs... So I'm asking here:

Why do you prefer to use

array = []

Instead of


Is it just for the sake of be sure to have an empty array and avoid a possible error? as in

NoMethodError (undefined method `clear' for nil:NilClass)

If you know the array variable is an Array type, do you still avoid the `clear` method?

@esparta Never used .clear

I use

[].tap |x| do / end

quite a lot tho

@fjfish that's a use case, I've see a lot different ones on a loop as in...

array = []
elements.each do |element|
if some_reason
array = [] # instead of array.clear
# more things


Sounds like not using select or find or some of the other enumerable methods

Can also create a lambda and use & to keep it sweet too

Or use &method(:thing) if lambdas don't suit


@fjfish yes, must of the time I've see plain arrays initialized and loops with logic, but still, why not using the .clear is not clear to me.
Maybe at some point it had race conditions?
Or maybe people is not aware of .clear exist and making it on C-fashion looks familiar and convenient (as in let the GC do their job at some point).
That's why I'm asking.

Sign in to participate in the conversation

A Mastodon instance for Rubyists & friends