def search_result
categories.each_with_object([]) do |category, keywords|
keywords << category.keywords.split(', ').select{ |c| c.include?(query) } unless category.keywords.blank?
end.flatten.tally.first(3).map(&:first)
end[1, 2, 2, 3].tally
# => { 1 => 1, 2 => 2, 3 => 1 }%w(foo foo bar foo baz foo).tally
=> {"foo"=>4, "bar"=>1, "baz"=>1}%w(foo foo bar foo baz foo).map { |s| s[0] }.tally
=> {“f” => 4, “b” => 2}There’s discussion happening at the moment on accepting this feature, which would make the above syntax:
%w(foo foo bar foo baz foo).tally_by { |s| s[0] }
=> {“f” => 4, “b” => 2}list.group_by { |v| v.something }.transform_values(&:size)
list.group_by { |v| v.something }.map { |k, vs| [k, vs.size] }.to_h
list.group_by { |v| v.something }.to_h { |k, vs| [k, vs.size] }
list.each_with_object(Hash.new(0)) { |v, h| h[v.something] += 1 }
Counter caches
1)
Update Vote model
Now in the topics controller I can increment the up/down methods with
Increment
from the view
Decrement
Routes