Follow

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

array.clear

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
end
# more things
end

@esparta

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

@esparta also just occurred to me that if you were using tap you'd *have* to use clear

@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
Ruby.social

A Mastodon instance for Rubyists & friends