ruby - Sorting/accessing through an array of nested hashes -


i have array of hashes names , ages:

array = [ {"bill" => 12}, {"tom" => 13}, {"pat" => 14} ] 

i realize that, calling first method, happens:

array.first # => {"bill" => 12} 

without defining class, i'd do:

array.first.name # => "bill" 

how can that?

doing:

def name   array[0].keys end  

will define private method, can't called on receiver.

since array array consists of hashes, when array.first hash returned {"bill" => 12}.

you can define method hash#name can applied array.first (a hash)

here:

class hash   def name     self.keys.first   end end  array.first.name # => "bill"  #to print names array.each{|a| puts a.name} # bill # tom # pat  # or collect them in array array.map(&:name) #  => ["bill", "tom", "pat"]  

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -