Allen Jz
Allen Jz

Reputation: 111

Does ruby have similiar multidimensional array like in 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

Upvotes: 0

Views: 96

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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}}}}}

Upvotes: 3

davidhu
davidhu

Reputation: 10452

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"}}}

Upvotes: 1

Related Questions