Skip to content

Instantly share code, notes, and snippets.

@ideasasylum
Created January 17, 2022 21:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ideasasylum/0cdfc898a09e9dd1a6fcd7f32d41762f to your computer and use it in GitHub Desktop.
Save ideasasylum/0cdfc898a09e9dd1a6fcd7f32d41762f to your computer and use it in GitHub Desktop.
Counts the frequency of characters in an AR collection
class CharacterFrequency
include Enumerable
# Take an AR collection and a block to extract the attribute value
def initialize collection, &block
@collection = collection
@block = block
end
def print
tally.sort.each { |k,v| puts "#{k} #{v}" }
end
# Yields each character from each record's attribute
def each
@collection.find_each do |item|
string = @block.call item
string.each_char { |c| yield c }
end
end
end
students = site.students.select :id, :email
chars = CharacterFrequency.new(students, &:email)
chars.tally
# => {"s"=>30398, "h"=>26312, "i"=>73951, "e"=>55701, "n"=>41233, "g"=>40669, "y"=>13222, "@"=>46768, "a"=>100846, "o"=>88959, "l"=>64128, "t"=>31600, "m"=>92564, "p"=>10249, "."=>60983, "u"=>17920, "v"=>8206, "r"=>38949, "c"=>58597, "f"=>7026, "z"=>4873, "k"=>13505, "-"=>1142, "d"=>19569, "w"=>5946, "b"=>12019, "1"=>6671, "7"=>3424, "0"=>5179, "8"=>3228, "2"=>4895, "6"=>2500, "x"=>2978, "9"=>3762, "j"=>7124, "_"=>2104, "5"=>2511, "3"=>3235, "4"=>2625, "q"=>853, "!"=>1, "+"=>38, "'"=>2}
chars.print
# ! 1
# ' 2
# + 38
# - 1142
# . 60983
# 0 5179
# 1 6671
# 2 4895
# 3 3235
# 4 2625
# 5 2511
# 6 2500
# 7 3424
# 8 3228
# 9 3762
# @ 46768
# _ 2104
# a 100846
# b 12019
# c 58597
# d 19569
# e 55701
# f 7026
# g 40669
# h 26312
# i 73951
# j 7124
# k 13505
# l 64128
# m 92564
# n 41233
# o 88959
# p 10249
# q 853
# r 38949
# s 30398
# t 31600
# u 17920
# v 8206
# w 5946
# x 2978
# y 13222
# z 4873
# => [["!", 1], ["'", 2], ["+", 38], ["-", 1142], [".", 60983], ["0", 5179], ["1", 6671], ["2", 4895], ["3", 3235], ["4", 2625], ["5", 2511], ["6", 2500], ["7", 3424], ["8", 3228], ["9", 3762], ["@", 46768], ["_", 2104], ["a", 100846], ["b", 12019], ["c", 58597], ["d", 19569], ["e", 55701], ["f", 7026], ["g", 40669], ["h", 26312], ["i", 73951], ["j", 7124], ["k", 13505], ["l", 64128], ["m", 92564], ["n", 41233], ["o", 88959], ["p", 10249], ["q", 853], ["r", 38949], ["s", 30398], ["t", 31600], ["u", 17920], ["v", 8206], ["w", 5946], ["x", 2978], ["y", 13222], ["z", 4873]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment