why does the initialize method not return the last expression?

A

aidy

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
 
S

Sebastian Hungerecker

aidy said:
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
 
X

Xavier Noria

Why is this not the case for the initialize method?

class Browser

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

end

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.
 
M

Michael Guterl

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")

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 Guterl
 
T

Thomas Wieczorek

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top