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?

3
  • is it necessary to imperatively modify "access" or it can be defined in one step? Commented Jun 24, 2011 at 16:13
  • Out of curiosity, what resources have you been using to learn Ruby (apart from Stack Overflow)? Commented Jun 25, 2011 at 0:45
  • 1
    To learn Ruby i am doing web-project on ROR. Some answers i got from Programming Ruby 1.9 book, some in google and some here. Commented Jun 25, 2011 at 10:52

5 Answers 5

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"
Sign up to request clarification or add additional context in comments.

Comments

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'

Comments

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.

Comments

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.

Comments

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.