Skip to content

Instantly share code, notes, and snippets.

@compwron
Created February 2, 2015 05:16
Show Gist options
  • Select an option

  • Save compwron/08c3ff80abd4b0425abe to your computer and use it in GitHub Desktop.

Select an option

Save compwron/08c3ff80abd4b0425abe to your computer and use it in GitHub Desktop.
samples
l = [
"John",
"John",
"John",
"John",
"Adam",
"Adam",
"Adam",
"Linda",
"Bob",
# ---------
"Susan",
"Susan",
"Susan",
"Susan"
"Adam",
"Adam",
"Adam",
# ......
]
# "Adam - 3"
largest_count = 0
largest_item = "default"
r = l.inject({}) {|agg, item|
agg[item].nil? ? agg[item] = 1 : agg[item] += 1
current_count = agg[item]
if current_count > largest_count
largest_item = item
largest_count = current_count
end
agg
}
r # {}
# r1, r2
r1.get(r2.largest) = agg_r2_largest
puts "#{largest_item} - #{largest_count}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment