How can i change this:
array_of_hash = [{"month"=>"January", "count"=>67241},
{"month"=>"February", "count"=>60464},
{"month"=>"March", "count"=>30403}]
To this :
month = ["January", "February", "March"]
count = [67241, 60464,30403]
To extract a single value (eg 'month'
), you could use map
:
array_of_hash.map { |hash| hash['month'] }
#=> ["January", "February", "March"]
Which can be extended to return the values for both, 'month
and 'count'
:
array_of_hash.map { |h| [h['month'], h['count']] }
#=> [["January", 67241], ["February", 60464], ["March", 30403]]
There's also a method to fetch multiple values at once – values_at
:
array_of_hash.map { |h| h.values_at('month', 'count') }
#=> [["January", 67241], ["February", 60464], ["March", 30403]]
The resulting array can then be rearranged via transpose
:
array_of_hash.map { |h| h.values_at('month', 'count') }.transpose
#=> [["January", "February", "March"], [67241, 60464, 30403]]
The two inner arrays can be assigned to separate variables using Ruby's array decomposition :
months, counts = array_of_hash.map { |h| h.values_at('month', 'count') }.transpose
months #=> ["January", "February", "March"]
counts #=> [67241, 60464, 30403]
A simple solution is to iterate the array of hashes and add the required values to two separate arrays:
months = []
counts = []
array_of_hash.each do |hash|
months << hash["month"]
counts << hash["count"]
end
But you could also use each_with_object
months, count = array_of_hash.each_with_object([[], []]) do |hash, accu|
accu[0] << hash["month"]
accu[1] << hash["count"]
end
or iterate twice and get the months and counts separately:
months = array_of_hash.map { |hash| hash["month"] }
counts = array_of_hash.map { |hash| hash["count"] }
months, counts =
array_of_hash.
flat_map(&:values).
partition(&String.method(:===))
months, counts =
%w|month count|.map { |key| array_of_hash.map { |h| h[key] } }
month = []
count = []
array_of_hash.each do |hash|
month << hash['month']
count << hash['count']
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.