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

时间:2016-09-21 02:35:20

标签: php arrays ruby

像在php中一样:

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

也许使用哈希?以前从没用过红宝石:)

当我打字代码时:

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'

出现

错误

  input['cdef']['c'] = 'C'
消息:

[]=' for nil:NilClass

2 个答案:

答案 0 :(得分:3)

虽然@ davidhu2000的答案或多或少是正确的,但我会选择更强大的解决方案:在构造函数中使用default_procdup.clear魔法是递归地将default_proc传递给深层嵌套的元素:

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

这样一个人不需要丑陋的冗余任务:

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

Ninja任务:

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 :(得分:1)

要修复错误,您需要在分配键值对之前初始化空哈希。

updateMotionHistory(silh, mhi, timestamp, MHI_DURATION);
calcMotionGradient(mhi, mask, orient, MAX_TIME_DELTA, MIN_TIME_DELTA, 3);
segmentMotion(mhi, segmask, regions, timestamp, MAX_TIME_DELTA);