@fathers 해시 배열이 있습니다.
a_father = { "father" => "Bob", "age" => 40 }
@fathers << a_father
a_father = { "father" => "David", "age" => 32 }
@fathers << a_father
a_father = { "father" => "Batman", "age" => 50 }
@fathers << a_father
이 배열을 검색하고 블록이 true를 반환하는 해시 배열을 어떻게 반환합니까?
예를 들면 다음과 같습니다.
@fathers.some_method("age" > 35) #=> array containing the hashes of bob and batman
감사.
답변
Enumerable # select (이라고도 함 find_all
)를 찾고 있습니다 .
@fathers.select {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
# { "age" => 50, "father" => "Batman" } ]
문서에 따르면, “[이 경우 열거 가능한 @fathers
블록 의 모든 요소를 포함하는 배열이 거짓이 아닌” 배열을 반환합니다 . “
답변
이것은 첫 번째 경기를 반환합니다
@fathers.detect {|f| f["age"] > 35 }
답변
배열이 다음과 같은 경우
array = [
{:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
{:name => "John" , :age => 26 , :place => "xtz"} ,
{:name => "Anil" , :age => 26 , :place => "xsz"}
]
그리고 배열에 어떤 값이 이미 있는지 알고 싶습니다. 찾기 방법 사용
array.find {|x| x[:name] == "Hitesh"}
Hitesh가 이름에 있으면 객체를 반환하고 그렇지 않으면 nil을 반환합니다