Reputation: 9
In my code I have a hash, each one with a set value of 0, after running through the code, I would like it to display "1", but it only displays a 0. Can anyone help, and please explain my error and why it didn't work.
puts "Hello!, and welcome to the 'Coin Calculator V1.0', please enter a value."
coin_value = gets.to_i
coin_num = {"quarters" => 0,"dimes" => 0,"nickels" => 0,"pennies" => 0}
if coin_value>25
coin_value-25
coin_num["quarters"]+1 // **basically, how do I add an integer value to the old integer?
puts coin_num["quarters"]
end
Upvotes: 0
Views: 68
Reputation: 95252
Neither of your arithmetic expressions changes anything.
coin_value - 25
That evaluates to 25 less than coin_value
; if you printed it out or assigned it somewhere, you would see that. But since you don't do anything with the value, it just gets thrown away and nothing happens. Certainly, coin_value
doesn't change.
Similarly,
coin_num["quarters"] + 1
evaluates to one more than the current value of coin_num["quarters"]
, but doesn't change anything.
If you want to change the value of a variable - any variable, whether a simple scalar like coin_value
or an element of a Hash or Array - you have to use an assignment statement. You need an =
, and the variable you want to change has to be on the left hand side of that =
:
coin_value = coin_value - 25
coin_num['quarters'] = coin_num['quarters'] + 1
Ruby does define shorthand operators for modifying a variable using a simple expression involving that same variable's previous value:
coin_value -= 25
coin_num['quarters'] += 1
But you're still using =
- it's just part of a compound assignment operator now.
Upvotes: 0
Reputation: 12558
coin_num["quarters"] = coin_num["quarters"] + 1
which can be shortened using the +=
operator (addition assignment):
coin_num["quarters"] += 1
Upvotes: 2