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?

+3


source to share


3 answers


The default value for each key in this Hash

is 0

, so

frequencies[k] += 1

      

You are incrementing every (non-existent key) value from 0

to 1

.



An easy fix is ​​to use an external counter as a value:

counter = 0
words.each do |k|
    frequencies[k] = counter
    counter += 1
end

      

+2


source


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

      

+1


source


frequencies

seems to be the wrong choice of variable name from description.

Any reason you can't just

words = "foo bar baz"
=> "foo bar baz"
words.split.map.with_index.to_h
=> {"foo"=>0, "bar"=>1, "baz"=>2}

      

0


source







All Articles