2010-02-11 16 views
191

Ho una matrice di hash, @fathers.Come faccio a cercare all'interno di un array di hash per valori hash in ruby?

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 

Come posso cercare questo array e restituire un array di hash per il quale un blocco restituisce true?

Ad esempio:

@fathers.some_method("age" > 35) #=> array containing the hashes of bob and batman 

Grazie.

risposta

346

Siete alla ricerca di Enumerable#select (chiamato anche find_all):

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

Per la documentazione, "restituisce un array contenente tutti gli elementi del [l'enumerabile, in questo caso @fathers] per il quale blocco non è falso ".

+12

Oh! Eri il primo! Cancellando la mia risposta e +1. –

+1

Eccellente. Grazie molto! – doctororange

+13

Come nota, se si voleva trovare solo uno (il primo) si può usare '@fathers.find {| padre | padre ["età"]> 35} 'invece. –

165

questo tornerà prima partita

@fathers.detect {|f| f["age"] > 35 } 
+6

Lo preferisco a '# select' - Ma tutto vale per il tuo caso d'uso. '# detect' restituirà' nil' se non viene trovata alcuna corrispondenza, mentre '# select', nella risposta di @ Jordan, restituirà' [] '. –

+10

Si potrebbe anche usare 'find' invece di' detect' per un codice più leggibile –

+7

'find' può diventare confuso nelle rotaie, comunque. – user12341234

20

se la matrice sembra

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

e volete sapere se un certo valore è già presente nella propria matrice. Utilizzare Trova Metodo

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

Ciò restituirà oggetto se Hitesh è presente in nome altrimenti restituisce nil

Problemi correlati