Skip to content

Instantly share code, notes, and snippets.

@timurvafin
Created July 3, 2009 11:46
Show Gist options
  • Save timurvafin/140071 to your computer and use it in GitHub Desktop.
Save timurvafin/140071 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'activesupport'
class Hash
class Path
def initialize(hash)
@hash = hash
end
def [](path)
key, item = last_item(path)
item[symbolize_key(key)]
end
def []=(path, value)
key, item = last_item(path)
item[symbolize_key(key)] = value
end
private
def last_item(path)
path = path.split('/')
return path.pop, path.inject(@hash) { |hash, key| hash[symbolize_key(key)] }
end
def symbolize_key(key)
key.start_with?(':') ? eval(key) : key
end
end
def path
Path.new(self)
end
end
# read
puts({:a => {:b => :c}}.path[':a/:b'].inspect)
puts({'a' => {'b' => 'c'}}.path['a/b'].inspect)
puts({'a' => {:b => :c}}.path['a/:b'].inspect)
puts({'a' => {'b' => :c}}.path['a/b'].inspect)
# write
h = {'a' => {'b' => {}}}
h.path['a'] = 'test'
puts(h.inspect)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment