h8windows
h8windows

Reputation: 91

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.

Upvotes: 4

Views: 9766

Answers (2)

Mark Swardstrom
Mark Swardstrom

Reputation: 18080

present? may be what you're looking for...

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

Upvotes: 0

Naren Sisodiya
Naren Sisodiya

Reputation: 7288

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

Upvotes: 9

Related Questions