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

前端 未结 4 1338
别那么骄傲
别那么骄傲 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."

    0 讨论(0)
  • 2020-11-28 18:02

    if your array looks like

    array = [
     {:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
     {:name => "John" , :age => 26 , :place => "xtz"} ,
     {:name => "Anil" , :age => 26 , :place => "xsz"} 
    ]
    

    And you Want To know if some value is already present in your array. Use Find Method

    array.find {|x| x[:name] == "Hitesh"}
    

    This will return object if Hitesh is present in name otherwise return nil

    0 讨论(0)
  • 2020-11-28 18:08

    this will return first match

    @fathers.detect {|f| f["age"] > 35 }
    
    0 讨论(0)
  • 2020-11-28 18:16

    (Adding to previous answers (hope that helps someone):)

    Age is simpler but in case of string and with ignoring case:

    • Just to verify the presence:

    @fathers.any? { |father| father[:name].casecmp("john") == 0 } should work for any case in start or anywhere in the string i.e. for "John", "john" or "JoHn" and so on.

    • To find first instance/index:

    @fathers.find { |father| father[:name].casecmp("john") == 0 }

    • To select all such indices:

    @fathers.select { |father| father[:name].casecmp("john") == 0 }

    0 讨论(0)
提交回复
热议问题