0

i have method, which returns either an array (if it contains any elements) or false if it is nil:

def check_for_four
    @four = []
    check_values.each do |key, value|  ###check_values return hash with key and values as numbers
        @four << key if value == 4
    end

    if @four == nil
        return false
    else
        return @four
    end     
end

but later on, if i call a method

if some_object.check_for_four
    puts "true"
else
    puts "false"
end

it always return true, even if @four array is empty. Why is that?

1
  • nil and empty are not the same thing Commented Feb 22, 2013 at 16:09

2 Answers 2

3

You are checking for whether the array is nil (i.e. is the singleton instance of NilClass) which is very different to checking whether the array is empty.

To check where the array is empty you can either call empty? or if you actually want to check whether it is not empty, you can also use any?.

You can of course also do things like check that the length/size is zero, but it feels more rubyish to me to ask for the specific thing you are interested in.

Sign up to request clarification or add additional context in comments.

Comments

0

An empty array is 'truthy' in Ruby. For example:

puts "foo" if []

will output "foo" but

puts "foo" if nil

won't output anything.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.