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

···

--
Posted via http://www.ruby-forum.com/.

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

···

On Fri, Oct 4, 2013 at 2:27 PM, Doug Jolley <lists@ruby-forum.com> 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

--
Dave Aronson, the T. Rex of Codosaurus LLC,
secret-cleared freelance software developer
taking contracts in or near NoVa or remote.
See information at http://www.Codosaur.us/\.

Quoting Doug Jolley (lists@ruby-forum.com):

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

···

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

--
  * Se la Strada e la sua Virtu' non fossero state messe da parte,
* K * Carlo E. Prelz - fluido@fluido.as che bisogno ci sarebbe
  * di parlare tanto di amore e di rettitudine? (Chuang-Tzu)

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

···

--
Posted via http://www.ruby-forum.com/\.

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

···

--
Posted via http://www.ruby-forum.com/.