Ruby - 在变量中存储列表数据的最佳方法

dmf*_*ari 1 ruby hash

我是Ruby的新手.我有这样的数据:

year | month |  foo 
--------------------
2016 |     2 |   4 
--------------------
2016 |     3 |  14 
--------------------
 ... |  ...  | ... 
--------------------
2017 |    12 |   9 
Run Code Online (Sandbox Code Playgroud)

我想将该表存储在变量中,并且仍然能够使用年和月列的值访问列foo中的数据.就像是:

data['2016']['2']
Run Code Online (Sandbox Code Playgroud)

得到'4'.

有没有办法做到这一点?

tad*_*man 5

通常最好将数字存储为数字,以便data[2016][2]在更理想的情况下.这导致了这样的结构:

data = {
  2016 => {
    2 => 4,
    3 => 14
  },
  2017 => {
    12 => 9
  }
}
Run Code Online (Sandbox Code Playgroud)

这是Ruby术语中的嵌套哈希结构.Ruby散列的好处是键可以是任何对象类型,并保留其类型.其他人会强制将键转换为字符串.

如果您希望将所有这些值作为字符串,欢迎将它们存储为字符串.请记住,整数值可以很容易地加在一起,字符串不能没有转换.例如:

total = data[2016].values.inject(:+)
# => 18
Run Code Online (Sandbox Code Playgroud)