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
就像在php中一样: p>
$ input = [
'a'=> 'A',
'b'=> 'B',
'cdef'=> [
'c'=> 'C',
'd'=> 'D',
'ef'=> [
'e'=> 'E',
'f'=> 'F'
]
]
]
code> pre>
也许使用哈希? 之前从未使用过ruby:) p>
当我输入代码时: p>
input = Hash.new
input ['a'] =' '
输入['b'] ='B'
input ['cdef'] ['c'] ='C'
input ['cdef'] ['d'] ='D'
input ['cdef ''['ef'] ['e'] ='E'
input ['cdef'] ['ef'] ['f'] ='F'
code> pre>
\ n 错误 p>
输入['cdef'] ['c'] ='C'
code> pre>
message: p>
[] ='对于nil:NilClass
code> pre>
div>
答
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}}}}}
答
To fix your error, you need to initialize an empty hash before assigning a key-value pair.
input = Hash.new
input['a'] = 'A' #=> {"a"=>"A"}
input['b'] = 'B' #=> {"a"=>"A", "b"=>"B"}
input['cdef'] = {} #=> {"a"=>"A", "b"=>"B", "cdef"=>{}}
input['cdef']['c'] = 'C' #=> {"a"=>"A", "b"=>"B", "cdef"=>{"c"=>"C"}}
input['cdef']['d'] = 'D' #=> {"a"=>"A", "b"=>"B", "cdef"=>{"c"=>"C", "d"=>"D"}}
input['cdef']['ef'] = {} #=> {"a"=>"A", "b"=>"B", "cdef"=>{"c"=>"C", "d"=>"D", "ef"=>{}}}
input['cdef']['ef']['e'] = 'E' #=> {"a"=>"A", "b"=>"B", "cdef"=>{"c"=>"C", "d"=>"D", "ef"=>{"e"=>"E"}}}
input['cdef']['ef']['f'] = 'F' #=> {"a"=>"A", "b"=>"B", "cdef"=>{"c"=>"C", "d"=>"D", "ef"=>{"e"=>"E", "f"=>"F"}}}