douluokuang7184 2016-01-25 01: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 01: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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了