In php i can do this:
$access = array();
$access['drivers']['create'] = 'administrator';
$access['drivers']['view'] = 'user';
echo $access['drivers']['view']; # => 'user'
How can i do it in Ruby?
In php i can do this:
$access = array();
$access['drivers']['create'] = 'administrator';
$access['drivers']['view'] = 'user';
echo $access['drivers']['view']; # => 'user'
How can i do it in Ruby?
It's Worth Noting that the convention is often to use :symbols instead of "strings"
access[:drivers][:view]
they are basically just immutable strings. Since strings are mutable objects in Ruby, hashes convert them to immutable ones internally ( to a symbol no less ) but you can do it explicitly and it looks a little cleaner in my opinion.
You could use the block form of Hash.new to provide an empty Hash as a default value:
h = Hash.new { |h,k| h[k] = { }; h[k].default_proc = h.default_proc; h[k] }
And then this happens:
>> h[:this][:that] = 6
# h = {:this=>{:that=>6}}
>> h[:other][:that] = 6
# {:this=>{:that=>6}, :other=>{:that=>6}}
>> h[:thing][:that] = 83724
# {:this=>{:that=>6}, :other=>{:that=>6}, :thing=>{:that=>83724}}
The funny looking default_proc stuff in the block shares the main hash's default value generating block with the sub-hashes so that they auto-vivify too.
Also, make sure you don't do this:
h = Hash.new({ })
to supply a hash as a default value, there is some explanation of why not over in this answer.