Undefined Method Complaint

Why does running the following code block result in a complaint that
there is no greeting method?

class MyClass
myVar=greeting()
def greeting()
return ‘Hello, world!’
end
end

Thanks so much for any help.

 ... doug

Subject: Undefined Method Complaint
Date: ven 04 ott 13 08:27:38 +0200

Quoting Doug J. ([email protected]):

Why does running the following code block result in a complaint that
there is no greeting method?

This line:

myVar=greeting()

invokes a class method, while you define an instance method. And, you
invoke the method before defining it.

Try:

class MyClass
def self.greeting()
return ‘Hello, world!’
end
myVar=greeting()
end

which does not print anything - but variable myVar now contains your
string. Add something like

puts myVar

to have the string printed on screen

Carlo

On Fri, Oct 4, 2013 at 2:27 PM, Doug J. [email protected]
wrote:

Why does running the following code block result in a complaint that
there is no greeting method?

class MyClass
myVar=greeting()
def greeting()
return ‘Hello, world!’
end
end

Because when you call greeting, greeting hasn’t been defined yet.
It won’t look ahead and see if you’re going to define it.

-Dave

Thanks so much for the help.

I know some languages have a declare-it-before-you-use-it philosophy. I
THOUGHT Ruby didn’t. Apparently, I’m wrong. My bad. I can’t believe
that I haven’t been bitten by this before.

Thanks again.

  ... doug

The upside of it is that Ruby lets you redefine methods on the fly, like
this:

def a
puts 1
end
=> nil

a
1
=> nil

def a
puts 2
end
=> nil

a
2
=> nil

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs