drouie2014 2016-09-21 02:35
浏览 25
已采纳

ruby在php中有类似的多维数组吗?

like in php:

$input = [
      'a' => 'A',
      'b' => 'B',
      'cdef' => [
             'c' => 'C',
             'd' => 'D',
             'ef' => [
                  'e' => 'E',
                  'f' => 'F'
             ]
      ]
]

maybe use Hash? never used ruby before :)

When I worte code:

input = Hash.new
input['a'] = 'A'
input['b'] = 'B'
input['cdef']['c'] = 'C'
input['cdef']['d'] = 'D'
input['cdef']['ef']['e'] = 'E'
input['cdef']['ef']['f'] = 'F'

error at

  input['cdef']['c'] = 'C'

message :

[]=' for nil:NilClass
  • 写回答

2条回答 默认 最新

  • dongyinju5977 2016-09-21 05:56
    关注

    Although the answer by @davidhu2000 is more or less correct, I would go with more robust solution: using default_proc in the constructor. The dup.clear magic is to recursively pass the default_proc through to deeply nested elements:

    input = Hash.new { |h, k| h[k] = h.dup.clear }
    input['a'] = 'A' 
    input['b'] = 'B' 
    input['cdef']['c'] = 'C' 
    input['cdef']['d'] = 'D' 
    input['cdef']['ef']['e'] = 'E' 
    input['cdef']['ef']['f'] = 'F' 
    
    input
    

    That way one does not need ugly redundant assignments:

    input['cdef'] = {}
    input['cdef']['ef'] = {} 
    

    Ninja assignment:

    input = Hash.new { |h, k| h[k] = h.dup.clear }
    input['a1']['a2']['a3']['a4']['a5'] = 42
    input
    #⇒ {"a1" => {"a2" => {"a3" => {"a4" => {"a5" => 42}}}}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 web课程,怎么做啊😭没好好听课 根本不知道怎么下手
  • ¥15 做一个关于单片机的比较难的代码,然后搞一个PPT进行解释
  • ¥15 python提取.csv文件中的链接会经常出现爬取失败
  • ¥15 数据结构中的数组地址问题
  • ¥15 maya的mel里,怎样先选择模型A,然后利用mel脚本自动选择有相同名字的模型B呢。
  • ¥15 Python题,根本不会啊
  • ¥15 会会信号与系统和python的来
  • ¥15 关于#python#的问题
  • ¥20 oracle RAC 怎么配置啊,配置
  • ¥15 excel 日常使用中出现问题