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?
With a hash.
access = Hash.new # or {}
access["drivers"] = {}
access["drivers"]["view"] = 'user'
You can use an array as the key if you want.
access = Hash.new
access["drivers", "view"] = "user"
You mean something like this?
#!/usr/bin/env ruby
access = Hash.new
access['drivers'] = Hash.new
access['drivers']['create'] = 'administrator'
access['drivers']['view'] = 'user'
puts access['drivers']['view'] # => 'user'
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.
From the question is unclear if you really need to update the structure. I'd most write something like this:
access = {
:drivers => {
:create => "administrator",
:view => "user",
},
}
access[:drivers][:view] #=> 'user'