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
ntalbott fb1f07049f * lib/ostruct.rb: Added OpenStruct#==.
* test/ostruct/test_ostruct.rb: Added.


git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@4596 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
2003-09-25 00:03:11 +00:00

59 lines
1.1 KiB
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.to_sym] = 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
if self.frozen?
raise TypeError, "can't modify frozen #{self.class}", caller(1)
end
mname.chop!
@table[mname.intern] = args[0]
elsif len == 0
@table[mid]
else
raise NoMethodError, "undefined method `#{mname}' for #{self}", caller(1)
end
end
def delete_field(name)
@table.delete name.to_sym
end
def inspect
str = "<#{self.class}"
for k,v in @table
str << " #{k}=#{v.inspect}"
end
str << ">"
end
attr_reader :table
protected :table
def ==(other)
return false unless(other.kind_of?(OpenStruct))
return @table == other.table
end
end