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

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

提交回复
热议问题