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
Post a Comment