How do I search within an array of hashes by hash values in ruby?

前端 未结 4 1412
别那么骄傲
别那么骄傲 2020-11-28 17:40

I have an array of hashes, @fathers.

a_father = { \"father\" => \"Bob\", \"age\" =>  40 }
@fathers << a_father
a_father = { \"father\" => \"Da         


        
4条回答
  •  误落风尘
    2020-11-28 17:59

    You're looking for Enumerable#select (also called find_all):

    @fathers.select {|father| father["age"] > 35 }
    # => [ { "age" => 40, "father" => "Bob" },
    #      { "age" => 50, "father" => "Batman" } ]
    

    Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers] for which block is not false."

提交回复
热议问题