Ryan
Ryan

Reputation: 65

Please help me understand this Ruby code

I've been working at an online course and I was wondering if someone could break down what is going on with the .each function in this code.

puts "Enter data"
text = gets.chomp
words = text.split

frequencies = Hash.new(0)

words.each { |word| frequencies[word] += 1 }

Upvotes: 0

Views: 66

Answers (1)

victorkt
victorkt

Reputation: 14552

Here is the break down:

# 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 }

In the end you will have a Hash where each key is a word in text and the values are the number of times each word appeared.

Upvotes: 3

Related Questions