Home > Software design >  Select filed from Array of Hashes in Ruby
Select filed from Array of Hashes in Ruby

Time:01-15

So i have this Array of Hashes

{"id"=>50823, "code"=>"1PLAK", "name"=>"Eselente", "order"=>1}
{"id"=>74327, "code"=>"1MAGP", "name"=>"Mango", "order"=>2}
{"id"=>50366, "code"=>"1ANGC", "name"=>"Tabnie", "order"=>3}
{"id"=>76274, "code"=>"1FABD", "name"=>"Slamtab", "order"=>4}

And i want to select the field order (just one field at the same time) for comparing afterwards. What's the correct way to do it? Thanks!

CodePudding user response:

When you only want to extract the values of the orders then I would do this:

array = [
  {"id"=>50823, "code"=>"1PLAK", "name"=>"Eselente", "order"=>1},
  {"id"=>74327, "code"=>"1MAGP", "name"=>"Mango", "order"=>2},
  {"id"=>50366, "code"=>"1ANGC", "name"=>"Tabnie", "order"=>3},
  {"id"=>76274, "code"=>"1FABD", "name"=>"Slamtab", "order"=>4},
]
array.map { |hash| hash["order"] }
#=> [1, 2, 3, 4]

When you are only interested in the very first value (1 like you wrote in the comments above) then you can do:

array.first["order"] # or array[0]["order"]
#=> 1
  •  Tags:  
  • Related