0

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?

Andrew Grimm
  • 74,534
  • 52
  • 194
  • 322
Vladimir Tsukanov
  • 3,869
  • 7
  • 27
  • 33

5 Answers5

2

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"
Andrew Grimm
  • 74,534
  • 52
  • 194
  • 322
2

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'
HelmuthB
  • 471
  • 5
  • 10
2

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.

Andrew Grimm
  • 74,534
  • 52
  • 194
  • 322
loosecannon
  • 7,643
  • 3
  • 30
  • 43
1

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.

Community
  • 1
  • 1
mu is too short
  • 413,090
  • 67
  • 810
  • 771
0

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'
tokland
  • 63,578
  • 13
  • 136
  • 167