Converting Ruby hashes to arrays
If you want to modify the original hash you can do:
hash.each_pair { |key, value| hash[key] = value.to_a }
From the documentation for Hash#to_aConverts hsh to a nested array of [
key, value ] arrays.
h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
h.to_a #=> [["c", 300], ["a", 100], ["d", 400]]
Convert array of hashes to array
a=[{:code=>"404"}, {:code=>"302"}, {:code=>"200"}]
puts a.map{|x|x.values}.flatten.inspect
output["404", "302", "200"]
Convert hash to array of hashes
Leveraging Array#transpose and Array#to_h
keys = list.keys
list.values.transpose.map { |v| keys.zip(v).to_h }
ruby: how to convert hash into array
try this:
{0=>0.07394653730860076, 1=>0.0739598476853163, 2=>0.07398647083461522}.to_a
#=> [[0, 0.07394653730860076], [1, 0.0739598476853163], [2, 0.07398647083461522]]
Ruby Hash to array of values
Also, a bit simpler....
>> hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
=> {"a"=>["a", "b", "c"], "b"=>["b", "c"]}
>> hash.values
=> [["a", "b", "c"], ["b", "c"]]
Ruby doc here Array to Hash Ruby
a = ["item 1", "item 2", "item 3", "item 4"]
h = Hash[*a] # => { "item 1" => "item 2", "item 3" => "item 4" }
That's it. The *
is called the splat operator.One caveat per @Mike Lewis (in the comments): "Be very careful with this. Ruby expands splats on the stack. If you do this with a large dataset, expect to blow out your stack."
So, for most general use cases this method is great, but use a different method if you want to do the conversion on lots of data. For example, @Łukasz Niemier (also in the comments) offers this method for large data sets:
h = Hash[a.each_slice(2).to_a]
Ruby get object keys as array
hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.keys #=> ["apple", "carrot"]
it's that simple
Related Topics
Automatically Adding Proxy to All Http Connections in Ruby
Gem Install Rmagick Fails on Os X El Capitan
Sorting Hash of Hashes by Value (And Return The Hash, Not an Array)
Convert Durations in Ruby - Hh:Mm:Ss.Sss to Milliseconds and Vice Versa
Encoding Problems in Rails on Ruby 1.9.1
Rake Cucumber and Rake Spec Always Use "Develop" Environment
Accessing Microsoft Exchange Server from Ruby
Issue Installing Gems on Windows 7 with Proxy
Where to Reopen a Class in Ror
Regex to Check Alphanumeric String in Ruby
How to Tell Unicorn to Understand Heroku's Signals