1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00
ruby--ruby/lib/ostruct.rb
nobu 29cef5f795 use Object#class instead of deprecated Object#type.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@2927 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
2002-10-02 16:45:35 +00:00

55 lines
952 B
Ruby

# 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.class == Fixnum
name = name.id2name
end
@table.delete name
end
def inspect
str = "<#{self.class}"
for k,v in @table
str += " "
str += k
str += "="
str += v.inspect
end
str += ">"
str
end
end