Skip to content

Instantly share code, notes, and snippets.

@dorkalev
Last active December 23, 2015 08:29
Show Gist options
  • Save dorkalev/6608204 to your computer and use it in GitHub Desktop.
Save dorkalev/6608204 to your computer and use it in GitHub Desktop.
sentence = "there is a wild rose"
letters = sentence.gsub(' ','').split(//)
letters_counter = {}
letters.each do |letter|
letters_counter[letter] ||= 0
letters_counter[letter] += 1
end
letters_counter = letters.each_with_object({}) do |letter, a|
a[letter] ||= 0
a[letter] += 1
end
letters_counter = letters.each_with_object(Hash.new(0)) do |letter, a|
a[letter] += 1
end
require 'yaml'
puts letters_counter.to_yaml
RESULT:
---
t: 1
h: 1
e: 3
r: 2
i: 2
s: 2
a: 1
w: 1
l: 1
d: 1
o: 1
@rab
Copy link

rab commented Sep 23, 2013

sentence.downcase.scan(/[a-z]/).each_with_object(Hash.new(0)) {|letter, counts| counts[letter] += 1}

Using downcase.scan(/[a-z]/) avoids other non-letter characters besides space.

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