damianesteban
damianesteban

Reputation: 1611

How do I split a hash into two arrays based on key and value in Ruby?

So I am trying to split a Hash into two Arrays, one with the keys and one with the values.

So far I have:

hash = { Matsumoto: "Ruby", Ritchie: "C", Backus: "Fortran", McCarthy: "Lisp" }

Im able to make an array out of keys or values like so:

hash.map { |creator, proglang| creator }

But I'm unable to make two arrays, one containing the keys and one containing the values. I've played around with a number of methods and I'm at a loss.

Thank you.

Upvotes: 0

Views: 1951

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110685

keys, values = hash.to_a.transpose
  #=> [[:Matsumoto, :Ritchie, :Backus  , :McCarthy],
  #    ["Ruby"    , "C"     , "Fortran", "Lisp"   ]] 

also works, but keys() and values() are provided for this very task.

Upvotes: 0

Farrukh Abdulkadyrov
Farrukh Abdulkadyrov

Reputation: 717

You can refer to Hash class methods:

hash.keys
hash.values

which return arrays of keys and values respectively

See http://www.ruby-doc.org/core-2.1.0/Hash.html for more details

Upvotes: 1

Rafa Paez
Rafa Paez

Reputation: 4860

keys, values = hash.keys, hash.values

 > keys
 # => [:Matsumoto, :Ritchie, :Backus, :McCarthy] 
 > values
 # => ["Ruby", "C", "Fortran", "Lisp"] 

Upvotes: 4

Related Questions