Convert a string to a hash : split « String « Ruby

Convert a string to a hash

text = 'The rain in Spain falls mainly in the plain.'
word_count_hash = 0
p word_count_hash
text.split(/\W+/).each { |word| word_count_hash[word.downcase] += 1 }
p word_count_hash
# => {"rain"=>1, "plain"=>1, "in"=>2, "mainly"=>1, "falls"=>1,
#     "the"=>2, "spain"=>1}


Related examples in the same category

1.split a string into multiple pieces
2.split method can split on newlines, or multiple characters at once, to get a cleaner result
3.Splitting Strings into Arrays with scan
4.Paragraphs counter by split method
5.Split one by one
6.Split a string, reverse the sequence and append them again
7.Split with by one or more space