rib3ye
rib3ye

Reputation: 2923

Why does the addition operator append hash key-value pairs?

I'm new to programming and trying to make sense of why an operator almost always use for addition, appends a hash key-value pair in Ruby.

The following code snippet is from the Pragmatic Studio Ruby course:

letters = {"c" => 3, "e" => 1, "l" => 1, "n" => 1, "t" => 1, "x" => 8, "y" => 4}
point_totals = Hash.new(0)

"excellently".each_char do |char|
    point_totals[char] += letters[char]
end

puts point_totals
puts point_totals.values.reduce(0, :+)

Output

{"e"=>3, "x"=>8, "c"=>3, "l"=>3, "n"=>1, "t"=>1, "y"=>4}
23

Why does the language use += instead of <<?

Upvotes: 0

Views: 92

Answers (2)

August
August

Reputation: 12558

You're not appending a key-value pair, you're incrementing the value associated with the char key in the points_total hash.

Upvotes: 1

rohit89
rohit89

Reputation: 5773

You have += because you are adding the value of letters[char] to points_total[char]

<< is used for appending to an array.

Upvotes: 2

Related Questions