Allen Jz - 11 months ago 38

PHP Question

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`

Answer Source

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