Skip to content

Instantly share code, notes, and snippets.

@mathie
Created February 4, 2012 12:19
Show Gist options
  • Save mathie/1737500 to your computer and use it in GitHub Desktop.
Save mathie/1737500 to your computer and use it in GitHub Desktop.
Given a string, tell me how many of each character I'll need. Surprisingly useful when trying to typeset a sentence and check to see if you've enough type!
#!/usr/bin/env ruby
puts "Gies a phrase"
str = STDIN.readline.chomp
characters = Hash.new(0)
str.each_char do |char|
characters[char] += 1
end
characters.sort_by { |k, v| v }.reverse.each do |key, val|
puts "#{key}: #{val}"
end
@caius
Copy link

caius commented Feb 4, 2012

Just because I'm in a pub and therefore can't resist evil things like inject and chaining enumerable methods together...

#!/usr/bin/env ruby

puts "Gies a phrase"
STDIN.readline.chomp.each_char.inject(Hash.new(0)) do | characters, char |
  characters[char] += 1
  characters
end.sort do | (ak,av), (bk, bv) |
  bv <=> av
end.each do | char, freq |
  puts "#{char}: #{freq}"
end

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