On Wednesday 14 January 2004 05:04 am, Mike Williams wrote:
> ----
> 1. SettingAttributes
>
> The obvious way is just to create the instance, and then call
> writer-methods to set attributes, e.g.
>
> class Link
> def initialize(url, content)
> @url = url
> @content = content
> end
> attr_accessor :url, :content, :link, :target
> end
>
> link = Link.new(url, "here")
> link.title = "the whole story"
>
> ----
I might point out another means, not so well explored, through the use of
singletons and runtime typing if required (read 'duck typing' for the less
squeamish) as follows:
class Link
def initialize(url, content)
@url = url
@content = content
end
end
link = Link.new(url, "here")
def link.title; "the whole story"; end
One of the interesting things to note about this approach is that class code
responsible for assignment is in no way needed, and tests for the available
singleton can be easily done through respond_to? (hence the typing).
--
T.