Skip to content

Instantly share code, notes, and snippets.

@ecin
Created October 16, 2013 16:43
Show Gist options
  • Save ecin/7010960 to your computer and use it in GitHub Desktop.
Save ecin/7010960 to your computer and use it in GitHub Desktop.
OStruct-like that raises raises error on non-existent keys.
class OHash < Hash
def initialize(key_values)
key_values.each { |key, value| self[key] = value }
end
def method_missing(key)
if self.has_key?(key)
return self[key]
else
raise NoMethodError
end
end
end
struct = OHash.new(:a => 1, :b => 2)
struct.a # => 1
struct.b # => 2
struct.c # => NoMethodError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment