Skip to content

Instantly share code, notes, and snippets.

@secretpray
Last active February 28, 2024 16:49
Show Gist options
  • Save secretpray/cbbb2bb6d4a1a8261ec9fec4661d0b32 to your computer and use it in GitHub Desktop.
Save secretpray/cbbb2bb6d4a1a8261ec9fec4661d0b32 to your computer and use it in GitHub Desktop.
New tally method (Ruby 2.7)
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}

alternative

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 }
@secretpray
Copy link
Author

PS Search with Sphinx

class SearchService
  SEARCH_TYPES = %w[all question answer comment user].freeze

  def self.call(params)
    new(params).search
  end

  def initialize(params)
    @search_query = params[:search_query]
    @search_by    = params[:search_by]
  end

  def search
    return [] if @search_query.blank? || !SEARCH_TYPES.include?(@search_by)

    if @search_by == 'all'
      ThinkingSphinx.search(@search_query)
    else
      Object.const_get(@search_by.capitalize).search(@search_query)
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment