5. Iterating over the Array


Can you help me please with this:
01. Use .each to iterate over the words array.
02. For each word we find, assume that the word itself is a key in frequencies and increment its value by 1.

Thank you.


You get the code

puts "Give me some text to work with."
# get a =text= from the input
text= gets.chomp
# split the =text= using the =space-character= as the separator
# the result will be a =list= containing all the =words= of the =text=
words=text.split(" ")
# with Hash.new() you create a new =hash=, 
#               newly added =key= will get default value =nil=
# with Hash.new(0) you create a new =hash=, 
#               newly added =key= will get default value =0=

each is a method

  • that accepts a block of code
  • then runs that block of code for every element in a list,
  • and the bit between do and end is just such a block.

A block is like an anonymous function or lambda.
The variable between pipe characters is the parameter for this block.
words.each { |woord| frequencies[woord]+=1 }

words.each do | key |  frequencies[key] +=1 end 
puts frequencies
words.each { |key|  puts frequencies[key] }
for k,v in frequencies
   puts "#{k} \t#{v}"


5/8 Not adding
Iteration and Array to Hash conversion
Boa tarde,alguém me da uma luz para essa lição? Crie um Histograma lição 5 Iterando pelo array!