Ved
Ved

Reputation: 3500

nil v/s empty in ruby

I have the following code:

if([email protected]?) then
          logger.info ("Storing in recent search")
          logger.info(@stores.nil?)
          logger.info(@stores.empty?)
          logger.info(@stores)
          recentsearch = Recentsearch.create({:query => ss, :type=>tt, :ts=>Time.now})
          recentsearch.save
 end

So, if @stores is nil, the if-end should not execute. But strangely (for me) it does. In logs, I see the following :

Storing in recent search
nil
true
[]

How is this possible?

Upvotes: 0

Views: 241

Answers (2)

halfdan
halfdan

Reputation: 34214

Apparently @stores is not nil but initialized to an empty array [].

So [email protected]? is true because @stores.nil? is false. I'm not familiar with logger.info so I'm not sure why it prints nil for the third line. empty? returns true if there is no element in the array.

Upvotes: 2

Miki
Miki

Reputation: 7188

The condition in the first line says: if [email protected]? - if the stores is not nil.

Therefore, the line @stores.nil? must not evaluate to true. Indeed, it does not, it shows nil, which is (more-less) false. Meaning that @stores is not nil. The array is empty, but it is present, so everything seems ok.

nil signifies no object. Empty array is still an object.

Upvotes: 1

Related Questions