douluokuang7184 2016-01-25 09:16
浏览 200
已采纳

在Ruby中追加并增加哈希值

I have this hash :

hash = {:title=>"blabla", :content=>"blabla", :mark=>40}

In a loop I want to increment it with another pair of the same key => value objects.

What I want to have looks like this in PHP

    hash = array(
            0 => array(
              'title' => 'blabla',
              'content' => 'blabla',
              'mark' => 50,
            ),
            1 => array(
              'title' => 'blabla',
              'content' => 'blabla',
              'mark' => 50,
            )
     );

And to have that I would loop like that

foreach ($elements as $element) {
   $hash[] = array('title' => $element['title'],
                   'content' => $element['blabla'],
                   'mark' => $element['mark']
             );
}

The [] after the variable name, auto increments the array in php, but it doesn't seem to act the same way with Ruby.

The expected Ruby ouput would be the following :

hash = {
                {
                  'title' => 'blabla',
                  'content' => 'blabla',
                  'mark' => 50,
               },
                {
                  'title' => 'blabla',
                  'content' => 'blabla',
                  'mark' => 50,
               }
         }
  • 写回答

2条回答 默认 最新

  • dongqi0644 2016-01-25 09:35
    关注

    I think PHP's array/hash duality confuses you. A "hash with auto-incrementing keys" would be just an array in ruby. You can access its elements by their index (which is naturally auto-incremented).

    result = elements.map do |element|
      {
        'title' => element['title'],
        # ...
      }
    end
    
    result # [{'title' => 'foo'}, {'title' => 'bar'}, ...]
    result[0] # {'title' => 'foo'}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式