Converting Ruby Hashes to Arrays

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_a

Converts 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



Leave a reply



Submit