0

I am new to ruby and don't have much experience with hashes, I have a variable named tweets and it is a hash as such:

{"statuses"=>[{"metadata"=>{"result_type"=>"recent", "iso_language_code"=>"tl"}, "lang"=>"tl"}]}

I would like to save the array of information as a separate variable in an array. How would I go about this?

Puce
  • 1,003
  • 14
  • 28
cmart
  • 91
  • 2
  • 12

2 Answers2

1

Hash's have 2 very nice methods,

hash.values
hash.keys

in your case -

h = {"statuses"=>[{"metadata"=>{"result_type"=>"recent", "iso_language_code"=>"tl"}, "lang"=>"tl"}]}
p h.values
p.keys

These output arrays of each type. This might be what you want.

Also, this question will very well be closed. 1 Google search reported several Hash to Array SO questions.

Ruby Hash to array of values
Converting Ruby hashes to arrays

Community
  • 1
  • 1
ddavison
  • 28,221
  • 15
  • 85
  • 110
  • hash.values doesnt work because it creates a new array of the array. I cant have the extra array – cmart Jun 19 '13 at 15:01
0

If you have a Hash like so:

hash = {:numbers => [1,2,3,4]}

And you need to capture the array into a new variable. You can just access the key and assign it to a new variable like so:

one_to_five = hash[:numbers]

However, note that the new variable actually holds the array that is in the hash. So altering the hash's array alters the new variable's array.

hash[:numbers] << 6
puts one_to_five #=> [1,2,3,4,5,6]

If you use dup, it will create a copy of the array so it will be two separate arrays.

one_to_five = hash[:numbers].dup
hash[:numbers] << 6
puts one_to_five #=> [1,2,3,4,5]

So, in your case:

hash = {'statuses' => [{"metadata"=>{"result_type"=>"recent", "iso_language_code"=>"tl"}, "lang"=>"tl"}]}
new_array = hash['statuses'].dup

However, it would be interesting to see what it is you are wishing to accomplish with your code, or at least get a little more context, because this may not be the best approach for your final goal. There are a great many things you can do with Arrays and Hashes (and Enumerable) and I would encourage you to read through the documentation on them.

Charles Caldwell
  • 16,649
  • 4
  • 40
  • 47