0

I have array of hashes:

@array = [{:id => "1", :status=>"R"}, {:id => "1", :status=>"R"}, {:id => "1", :status=>"B"}, {:id => "1", :status=>"R"}] 

How to detect, does it contain in hashes with the value of status "B"? Like in simply array:

@array = ["R","R","B","R"] puts "Contain B" if @array.include?("B") 

3 Answers 3

6

Use any?:

@array.any? { |h| h[:status] == "B" } 
Sign up to request clarification or add additional context in comments.

Comments

2

Arrays (enumerables actually) have a detect method. It returns a nil if it doesn't detect anything, so you can use it like Andrew Marshall's any.

@array = [{:id => "1", :status=>"R"}, {:id => "1", :status=>"R"}, {:id => "1", :status=>"B"}, {:id => "1", :status=>"R"}] puts "Has status B" if @array.detect{|h| h[:status] == 'B'} 

1 Comment

I'd only really use detect over any? if I cared about finding the values that match the criteria as well, but it can certainly be used as a predicate method. (+1)
0

Just to add to what steenslag said:

detect doesn't always return nil.

You can pass in a lambda to execute (call) if detect does not 'detect' (find) an item. In other words, you can tell detect what to do if it can't detect (find) something.

To add to your example:

not_found = lambda { "uh oh. couldn't detect anything!"} # try to find something that isn't in the Enumerable object: @array.detect(not_found) {|h| h[:status] == 'X'} 

will return "uh oh. couldn't detect anything!"

This means that you don't have to write this kind of code:

if (result = @array.detect {|h| h[:status] == 'X'}).nil? # show some error, do something here to handle it # (this would be the behavior you'd put into your lambda) else # deal nicely with the result end 

That's one major difference between any? and detect -- you can't tell any? what to do if it doesn't find any items.

This is in the Enumerable class. ref: http://ruby-doc.org/core/classes/Enumerable.html#M003123

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.