From 90de52b4fdc72981be50b323fd650f6ca734d9e7 Mon Sep 17 00:00:00 2001 From: gsinclair Date: Thu, 19 Feb 2004 13:20:56 +0000 Subject: * lib/ostruct.rb: documented git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_8@5782 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 4 ++++ lib/ostruct.rb | 65 ++++++++++++++++++++++++++++++++++++++++++++++++---------- 2 files changed, 58 insertions(+), 11 deletions(-) diff --git a/ChangeLog b/ChangeLog index 03959d10f7..ba6e3d2b31 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,7 @@ +Thu Feb 19 22:19:00 2004 Gavin Sinclair + + * lib/ostruct.rb: documented + Thu Feb 19 21:28:00 2004 Gavin Sinclair * ext/strscan/strscan.c: improved documentation diff --git a/lib/ostruct.rb b/lib/ostruct.rb index eea7132ca0..786bd4de20 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -1,14 +1,48 @@ -# 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 +# +# = ostruct.rb: OpenStruct implementation +# +# Author:: Yukihiro Matsumoto +# Documentation:: Gavin Sinclair +# +# OpenStruct allows the creation of data objects with arbitrary attributes. +# See OpenStruct for an example. +# +# +# OpenStruct allows you to create data objects and set arbitrary attributes. +# For example: +# +# require 'ostruct' +# +# record = OpenStruct.new +# record.name = "John Smith" +# record.age = 70 +# record.pension = 300 +# +# puts record.name # -> "John Smith" +# puts record.address # -> nil +# +# It is like a hash with a different way to access the data. In fact, it is +# implemented with a hash, and you can initialize it with one. +# +# hash = { "country" => "Australia", :population => 20_000_000 } +# data = OpenStruct.new(hash) +# +# p data # -> +# class OpenStruct + # + # Create a new OpenStruct object. The optional +hash+, if given, will + # generate attributes and values. For example. + # + # require 'ostruct' + # hash = { "country" => "Australia", :population => 20_000_000 } + # data = OpenStruct.new(hash) + # + # p data # -> + # + # By default, the resulting OpenStruct object will have no attributes. + # def initialize(hash=nil) @table = {} if hash @@ -18,7 +52,7 @@ class OpenStruct end end - def method_missing(mid, *args) + def method_missing(mid, *args) # :nodoc: mname = mid.id2name len = args.length if mname =~ /=$/ @@ -37,10 +71,16 @@ class OpenStruct end end + # + # Remove the named field from the object. + # def delete_field(name) @table.delete name.to_sym end + # + # Returns a string containing a detailed summary of the keys and values. + # def inspect str = "<#{self.class}" for k,v in @table @@ -49,9 +89,12 @@ class OpenStruct str << ">" end - attr_reader :table + attr_reader :table # :nodoc: protected :table + # + # Compare this object and +other+ for equality. + # def ==(other) return false unless(other.kind_of?(OpenStruct)) return @table == other.table -- cgit v1.2.3