5. Iterating over the Array

Can you help me please with this:

  1. Use .each to iterate over the words array.
  2. For each word we find, assume that the word itself is a key in frequencies and increment its value by 1.

Thank you.

@sofiabadis,
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=
# 
frequencies=Hash.new(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}"
end

http://stackoverflow.com/questions/35177845/whats-the-difference-between-hash-new0-and
http://docs.ruby-lang.org/en/2.0.0/Hash.html
https://www.ruby-lang.org/en/documentation/quickstart/4/

5 Likes