我一直在网上课程工作,我想知道是否有人可以打破这段代码中的.each功能。
puts "Enter data"
text = gets.chomp
words = text.split
frequencies = Hash.new(0)
words.each { |word| frequencies[word] += 1 }
答案 0 :(得分:3)
以下是细分:
# Prints "Enter data" to the console
puts "Enter data"
# Ask for user input, remove any extra line breaks and save to text variable
text = gets.chomp
# Splits the text string to an array of words
words = text.split
# Create a new Hash, with default values of 0
frequencies = Hash.new(0)
# For each word in the array, increment 1 to the value in the frequencies hash.
# If the key doesn't exist yet, it will be assigned the value 0, since it is the default and then have 1 incremented to it
words.each { |word| frequencies[word] += 1 }
最后,你会得到一个哈希,其中每个键都是text
中的一个词,值是每个词出现的次数。