From: Eric Mahurin Date: 2005-08-09T02:21:57+09:00 Subject: Re: polymorphism and/or named parameters: the ruby way? --- "Berger, Daniel" wrote: > > -----Original Message----- > > From: Stephan Mueller [mailto:d454d@web.de] > > Sent: Saturday, August 06, 2005 12:01 PM > > To: ruby-talk ML > > Subject: polymorphism and/or named parameters: the ruby > way? > > > > > > Hello, > > > > i am kind of a newbi, please forgive me if i am asking > stale > > questions. > > > > I want to adjust the initialization of an object according > to > > the parameters given to new. > > A typical idiom for constructors is to do "yield self if > block_given?", > which I prefer over hash based arguments. For example: > > class Foo > attr_accessor :bar, :baz, :zap > def initialize > yield self if block_given? > end > end > > foo = Foo.new do |f| > f.bar = "hello" > f.baz = 5 > f.zap = "world" > end What's the advantage of this over: foo = Foo.new foo.bar = "hello" foo.baz = 5 foo.zap = "world" Is it method chaining? You want this thing to return foo? You could just end this statement list with "foo", or you could use "ensure": begin foo = Foo.new ensure foo.bar = "hello" foo.baz = 5 foo.zap = "world" end This begin..ensure..end expression returns foo (the result before ensure) not "world" as you might expect. Great for doing post operations after you calculate a return value (equivalent of C's i++ is another example). ____________________________________________________ Start your day with Yahoo! - make it your home page http://www.yahoo.com/r/hs