Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array .any? or .empty? conundrum in Rails

I'm attempting to check if there is anything at all in an array, and I'm confused about the results.

markets.any? do |m|
    m["market"]["name"] == "Atlanta"
end.should be_true

Returns You have a nil object when you didn't expect it!, You might have expected an instance of Array.

But

markets.empty? do |m|
    m["market"]["name"] == "Atlanta"
end.should be_false

Doesn't error. But it seems backwards to me, because I want to test for true, not false. And I don't get why .any? thinks it's nill. BTW, there are 3 items in the array, and none are nil.

like image 689
h8windows Avatar asked Jan 19 '23 06:01

h8windows


1 Answers

As per your comment, the market key is not present in hash, try following

markets.any? do |m|
    m["name"] == "Atlanta"
end.should be_true
like image 128
Naren Sisodiya Avatar answered Feb 07 '23 18:02

Naren Sisodiya