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

时间:2016-03-01 01:37:55

标签: ruby hash

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

year | month |  foo 
--------------------
2016 |     2 |   4 
--------------------
2016 |     3 |  14 
--------------------
 ... |  ...  | ... 
--------------------
2017 |    12 |   9 

我想将该表存储在变量中,并且仍然可以使用年份和月份列的值访问列foo中的数据。 类似的东西:

data['2016']['2']

得到'4'。

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:5)

通常最好将数字存储为数字,以便在更理想的情况下成为data = { 2016 => { 2 => 4, 3 => 14 }, 2017 => { 12 => 9 } } 。这导致了这样的结构:

total = data[2016].values.inject(:+)
# => 18

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

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

TcpClient Connector = new TcpClient();

                //If you can't connect, it takes you back here to try again.

                GetConnection:

            //Get the user to enter the IP of the server.

            Console.WriteLine("Enter server IP :");

            string IP = Console.ReadLine();

            //Attempt to connect; use a try...catch statement to avoid crashes.

            try
            {

                //Connect to the specified IP on port 2000

                Connector.Connect(IP, 2000);

                //So the program continues to receive commands.

                IsConnected = true;


                //Make Writer the stream coming from / going to Connector.

                Writer = Connector.GetStream();

                //We connected!

            }

            catch
            {

                //We couldn't connect :-(

                Console.WriteLine("Error connecting to target server! Press any key to try again.");

                Console.ReadKey();

                //Go back and start again!

                Console.Clear();

                goto GetConnection;

            }

答案 1 :(得分:1)

将其推送到哈希json并通过密钥&获取它值:

data = {
    "2016" => {
      "2" => "4",
      "3" => "1"
    },
    "2017" => {
      "12" => "9"
    }
  }

测试:数据['2016'] ['2']

结果:4