Why does the initialize method not return the last expression?

Hi,

In Ruby the last expression in a method is returned.

Why is this not the case for the initialize method?

class Browser

def initialize
ie ||= Watir::IE.new
end

end

ie = Browser.new

#goto is a url navigation method in Watir
#but I can’t do this

ie.goto(“www.gmail.com”)

Thanks

Aidy

aidy wrote:

In Ruby the last expression in a method is returned.

Why is this not the case for the initialize method?

It is.

class Foo
def initialize()
5
end
end
foo = Foo.send :allocate
foo.send :initialize
#=> 5

So you see that initialize does indeed return 5 here. Foo.new however
will not
return 5. This is quite simply due to the fact that new explicitly
returns
the newly created object, i.e. the call to initialize is not the last
thing
in new, so it’s not the return value of new.

HTH,
Sebastian

Like the others expressed, you can’t return a value with initialize.
You can add an instance variable which will represent your Watir
object.

class Browser
attr_reader :ie
def initialize
@ie ||= Watir::IE.new
end

end

and then:

browser = Browser.new
browser.ie.goto(“www.gmail.com”)

If you want to expand your Browser class with some custom methods and
redirect all other methods to Watir::IE, add
method_missing(methodname, *args) to it, e.g.

class Browser
attr_reader :ie
def initialize
@ie ||= Watir::IE.new
end

def method_missing(methodname, *args)
@ie.send(methodname, *args)
end
end

Regards, Thomas

On Sun, Aug 10, 2008 at 8:07 PM, aidy [email protected] wrote:

ie = Browser.new
Because you are not really calling initialize, you are calling new,
which is a different method. So you need to apply your reasoning to
#new.

new is a wrapper around initialize that returns an instance of the
class Browser, no matter what initialize returned.

On Sun, Aug 10, 2008 at 2:07 PM, aidy [email protected] wrote:

end

end

ie = Browser.new

#goto is a url navigation method in Watir
#but I can’t do this

ie.goto(“www.gmail.com”)

You have a few options. Depending on what you’re really trying to do.

Here is the simplest.

Browser = Watir::IE
ie = Browser.new
ie.goto(“www.gmail.com”)

Michael G.