Empty Array is True

There was a stage when a code like this was written in our Rails app


user = User.where(name: "John")

if user

    something.....

end

The question is will the something get executed only if there is a user named John in database, or it gets executed every time. Sadly it gets executed all the time.

So why it happens. Try this in your irb


>> puts "A" if []
A
=> nil
>> puts "A" unless [].empty?
=> nil
>> puts "A" if [].first
=> nil

So if you see, when we pass an  empty array to a condition, its always true!!!

You must remember it like this, even though a rack or shelf is empty, the shelf itself is a object, so its present, its the truth. In the next two examples, I have shown how to check and make things false if array is empty. So happy coding!

I think you can avoid all the array stuff hassel if you use the following type of code in Rails


user = User.find_by(name: "John")

if user

    something.....

end

OR, this one


user = User.where(name: "John").first

if user

    something.....

end

So. Enjoy life. Happy Coding.

, , , , , , ,

  1. #1 by Bowl on January 31, 2015 - 12:35 am

    You can use: [].present?
    This will return false if empty

  2. #2 by DanielPClark on February 1, 2015 - 3:08 am

    I prefer working with `where` and the empty Array result. Anything in Ruby is true other than nil and false. I don’t expect any query of a collection to ever be false. Bowl gave a good answer of [].present? … another good one is [].presence which will return nil for an empty Array, or the Array itself if it isn’t empty.

  3. #4 by sockmonk on February 3, 2015 - 2:10 pm

    If you just want to know if the user exists, but don’t actually need the user object in the code block that follows, then you should use User.where(name: “John”).exists? This clearly shows your intent, and is slightly more efficient because it doesn’t return all the columns in the users table, and doesn’t instantiate an ActiveRecord instance that has to be GC’d later.

  4. #6 by PareidoliaX on May 21, 2015 - 3:41 pm

    `u.any?` would also work in rails. I never found this behaviour surprising but I’ve been ruby, python, js exclusive for years. Is there a language where an empty array object is falsey?

Leave a reply to Karthikeyan Cancel reply