I have a array coming from a mysql query like this
section, views
aa, 2
aa, 100
bb, 2
bb, 3
bb, 100
and I am using this code to sort it
b = Hash.new(0)
array.each do |row|
....
....
b[section] += 1
end
which currently gives me a result hash for b[2]
aa,2
bb,3
Now I want the mysql query to filter the views for smaller and larger than 50 for example and would like the result to be
section,small,large
aa,1,1
bb,2,1
How do I implement this? Or would it be easier to do something like this:
aa_small,1
aa_large,1
bb_small,2
bb_large,1
ie keep them as separate hashes?
If I got it right you need something like:
views =
[['aa', 2],
['aa', 100],
['bb', 2],
['bb', 3],
['bb', 100]]
views
.group_by(&:first)
.map { |v, vs| [v, vs.partition { |_, x| x < 50 }
.map(&:length)] }
# => [["aa", [1, 1]], ["bb", [2, 1]]]
or if you want Hash:
Hash[views
.group_by(&:first)
.map { |v, vs| [v, vs.partition { |_, x| x < 50 }
.map(&:length)] }]
# => {"aa"=>[1, 1], "bb"=>[2, 1]}
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.