diff options
author | matz <matz@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 1998-01-16 12:19:09 +0000 |
---|---|---|
committer | matz <matz@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 1998-01-16 12:19:09 +0000 |
commit | 62e41d3f2e48422bbdf1bb2db83ae60b255b1a1a (patch) | |
tree | 4d0edb1c1986e1578b181ebe2441acfee27f1fab /lib/ostruct.rb | |
parent | 3db12e8b236ac8f88db8eb4690d10e4a3b8dbcd4 (diff) | |
download | ruby-62e41d3f2e48422bbdf1bb2db83ae60b255b1a1a.tar.gz |
Initial revision
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@8 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib/ostruct.rb')
-rw-r--r-- | lib/ostruct.rb | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/lib/ostruct.rb b/lib/ostruct.rb new file mode 100644 index 0000000000..f083677d8e --- /dev/null +++ b/lib/ostruct.rb @@ -0,0 +1,55 @@ +# ostruct.rb - Python Style Object +# just assign to create field +# +# s = OpenStruct.new +# s.foo = 25 +# p s.foo +# s.bar = 2 +# p s.bar +# p s + +class OpenStruct + def initialize(hash=nil) + @table = {} + if hash + for k,v in hash + @table[k] = v + end + end + end + + def method_missing(mid, *args) + mname = mid.id2name + len = args.length + if mname =~ /=$/ + if len != 1 + raise ArgumentError, "wrong # of arguments (#{len} for 1)", caller(1) + end + mname.chop! + @table[mname] = args[0] + elsif args.length == 0 + @table[mname] + else + raise NameError, "undefined method `#{mname}'", caller(1) + end + end + + def delete_field(name) + if name.type == Fixnum + name = name.id2name + end + @table.delete name + end + + def inspect + str = "<#{self.type}" + for k,v in @table + str += " " + str += k + str += "=" + str += v.inspect + end + str += ">" + str + end +end |