添加到哈希表中的值 [英] adding to the value in a hash table

查看:140
本文介绍了添加到哈希表中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将散列值加1。我的逻辑看起来是正确的,但由于某种原因,我的哈希值不会递增。

I am trying to increment the value in a hash by one. My logic seems right, but for some reason my value in the hash is not incrementing by one.

  puts item_sold
  temp = sales_hash.values[item_sold] + 1
  sales_hash.values[item_sold] = temp
  puts sales_hash.values[item_sold]

sales_hash 是一个散列,其中的密钥是一个介于1000-2000之间的数字,每个密钥的值从0开始。 item_sold 是1到15之间的随机数。散列中有15个项目。当 temp 打印出来时,它的值是1。但是,当我打印出 sales_hash.values [item_sold] 的值时,它会打印0.什么是 sales_hash.values [item_sold] 不递增?

sales_hash is a hash where the key is a number between 1000-2000 and the value for each key starts at 0. item_sold is a random number between 1 and 15. There are 15 items in the hash. When temp prints out it is a value of one. However when I print out the value of sales_hash.values[item_sold] it prints 0. What is sales_hash.values[item_sold] not incrementing?

推荐答案

Hash#values 返回所有散列值的数组。您想添加一个值,您可以这样做:

Hash#values returns an array of of all the hashes values. You want to add to one value, which you'd do like this:

item_sold
=> {0=>0, 1=>0, 2=>0}
item_sold[0] += 1
=> 1
item_sold
=> {0=>1, 1=>0, 2=>0}

您访问通过使用 hash [key] 语法获得散列值。

You access the value of a hash by by using the hash[key] syntax.

这篇关于添加到哈希表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆