Updating hash value in Ruby
What I would like to do is push a bunch of user-entered strings, separated by their spaces, onto Hash Keys, and assign each of those keys a numeric value from 0 upwards in the order they were entered. For example:
User input: "asdf b"
Result:
a => 0
b => 1
c => 2
d => 3
f => 4
b => 5
But my code only outputs 0 without incrementing, see my code below;
puts "Please enter data:"
text = gets.chomp
words = text.split(" ")
frequencies = Hash.new(0)
words.each do |k|
frequencies[k] += 1
end
frequencies.each do |x,y|
puts x + " " + y.to_s
end
Can anyone see what is wrong with the code above?
source to share
Your code doesn't work because
frequencies[k] += 1
how
frequencies[k] = frequencies[k] + 1
# ^ set new value ^ get default value (i.e. 0)
The default never changes, so each key gets the same default of 0 and adds it to it.
You can explicitly increase the default every time
words.each do |k|
frequencies[k] = frequencies.default += 1
end
But I think a more Ruby solution is to use key indices (since these are "numeric values"). each_with_index
gives you each key with a corresponding index, and to_h
turns those pairs into a hash.
frequencies = text.split.each_with_index.to_h
egwspiti is correct that older Ruby versions do not Enumerable#to_h
. In this case, you can do
words.each_with_index do |k, i|
frequencies[k] = i
end
source to share