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

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

提交回复
热议问题