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条)

报告相同问题?

悬赏问题

  • ¥200 比特币ord程序wallet_constructor.rs文件支持一次性铸造1000个代币,并将它们分配到40个UTXO上(每个UTXO上分配25个代币),并设置找零地址
  • ¥15 关于Java的学习问题
  • ¥15 如何使用chatgpt完成文本分类任务?
  • ¥15 已知速度v关于位置s的等式,怎么转化为已知位置求速度v的等式
  • ¥15 我有个餐饮系统,用wampserver把环境配置好了,但是后端的网页却进去,是为什么,能不能帮远程一下?
  • ¥15 R运行没有名称为"species"的插槽对于此对象类"SDMmodelCV"
  • ¥20 基于决策树的数字信号处理,2ask 2psk 2fsk的代码,检查下报错的原因
  • ¥15 wincc已组态的变量过多
  • ¥60 如图:直线与椭圆X轴平行,求直线与椭圆任意一点的相切坐标计算公式
  • ¥50 如何用python使用opencv里的cv::cudacodec::VideoWriter函数对视频进行GPU硬编码