diff options
author | marcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2012-10-28 21:20:10 +0000 |
---|---|---|
committer | marcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2012-10-28 21:20:10 +0000 |
commit | e44e356b53828d6468114b30e5c169296896f9b1 (patch) | |
tree | a24b67a505ccbba2f6b2204bcfc0aa6f7bdd3298 /lib/ostruct.rb | |
parent | 3785d2675abf2e4aca07e89596ea6f12b4c474a5 (diff) |
* lib/ostruct.rb: Add [] and []=, base on a patch by Thomas Sawyer
[ruby-core:42779] [Feature #6056]
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@37376 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib/ostruct.rb')
-rw-r--r-- | lib/ostruct.rb | 24 |
1 files changed, 22 insertions, 2 deletions
diff --git a/lib/ostruct.rb b/lib/ostruct.rb index 17b3ab05e2..b291f08308 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -176,18 +176,38 @@ class OpenStruct def method_missing(mid, *args) # :nodoc: mname = mid.id2name len = args.length - if mname.chomp!('=') && mid != :[]= + if mname.chomp!('=') if len != 1 raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1) end modifiable[new_ostruct_member(mname)] = args[0] - elsif len == 0 && mid != :[] + elsif len == 0 @table[mid] else raise NoMethodError, "undefined method `#{mid}' for #{self}", caller(1) end end + # Returns the value of a member. + # + # person = OpenStruct.new('name' => 'John Smith', 'age' => 70) + # person[:age] # => 70, same as ostruct.age + # + def [](name) + @table[name.to_sym] + end + + # + # Sets the value of a member. + # + # person = OpenStruct.new('name' => 'John Smith', 'age' => 70) + # person[:age] = 42 # => equivalent to ostruct.age = 42 + # person.age # => 42 + # + def []=(name, value) + modifiable[new_ostruct_member(name)] = value + end + # # Remove the named field from the object. Returns the value that the field # contained if it was defined. |