Skip to content

Instantly share code, notes, and snippets.

@deitrick
Last active December 11, 2015 04:58
Show Gist options
  • Save deitrick/4548726 to your computer and use it in GitHub Desktop.
Save deitrick/4548726 to your computer and use it in GitHub Desktop.
test_str = "Doo bee doo bee doo"
counted = Hash[test_str.downcase.split.map { |p| [p, 0] }]
#=> {"doo"=>0, "bee"=>0}
Desired output (counting number of times a word appears in a string, returned inside of a hash)
#=> {'doo' => 3, 'bee' => 2}
BOOM
h = Hash.new
words = test_str.downcase.split
words.each do |w|
if h.has_key?(w)
h[w] = h[w] + 1
else
h[w] = 1
end
end
return h
@fakefarm
Copy link

test_string = "Doo bee doo Bee doo"
converted_string = test_string.downcase.split(" ") 
converted_string.sort! { |a,b| b <=> a }

word_count = converted_string.inject({}) do |hash, word|  
  if hash.empty?
    hash[word] = 1  
  elsif hash.has_key?(word)
    hash[word] += 1
  else
    hash[word] = 1
  end
  hash
end

p word_count

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