I’m coding a simple text game to learn ruby. The hash has to be a global variable since I have to access it in other functions (There may be other solutions, but I could find this one). I’m trying to change values of hash elements. The function below basically increases the current price by 10%, and in its current form correctly changes the values and outputs them but fails to write them to the original hash.
$stocks = {"DOHOL" => 10, "GOZDE" => 5, "KONYA" => 20}
def margin
puts "New values:\n "
$stocks.each do|key, value|
percent = (value.to_i / 10) + 1
change = rand(percent)
value += change
puts "#{key}: #{value} USD"
end
end
I surely wish that I could make it to randomly decrease/increase the price by 10% but this is another challenge, I would like to solve by myself, so please do not comment on that one. More importantly, I have another question about hashes. Is there an obligation to use key and value, because googling tutorials, I have seen people using pairs like “name, value” or “person, name” instead of “key, value” without defining anything.
The
eachmethod from a hash will give you two things to work with in the block. It’s up to you how you name those things and you define the names between the ||’s.The new values have to be explicitly stored in the hash before the end of the block: