John
John

Reputation: 1

Why can't I call a method?

So I thought I'd learn some Ruby. I was playing with the interpreter but I wanted to make bigger programs so I downloaded Aptana, an IDE. When I try to run this code:

class HelloWorld
    def h
        puts "hello World!"
    end
    h
end

It gives me an error that says h is an undefined local variable. When I type the commands into the interpreter (without the class start and end) it calls h the way I want it to.

I'm at a loss here. what's going on?

Upvotes: 0

Views: 2922

Answers (3)

RubyFanatic
RubyFanatic

Reputation: 2281

Try this

class HelloWorld
  def self.h
    puts "hello World!"
  end
  h # you can only call h like this if it is defined as a class method above
end

HelloWorld.h # you can call the class method like this also

You need to define h as a class method to call it like that. ALternatively, you can do this

class HelloWorld
  def h
    puts "hello World!"
  end
end

a = HelloWorld.new # instantiate a new instance of HelloWorld
a.h

Good luck!

Upvotes: 0

Nathan Ostgard
Nathan Ostgard

Reputation: 8406

While defining a class, the methods you define are instance methods. This means you would call them like so:

class HelloWorld
  def h
    puts "hello world!"
  end
end

instance = HelloWorld.new
instance.h

Ruby is complaining that your method doesn't exist because, whilst defining a class body, any function calls made are to class methods (or singleton methods).

If you really wanted to do this, you would do it like so:

class HelloWorld
  def self.h
    puts "hello World!"
  end
  h
end

Upvotes: 3

Jonathan Sterling
Jonathan Sterling

Reputation: 18375

Your problem is that you've sent the h message whilst in class scope. (I'm sure some folks with more Ruby experience will want to correct my wording here; also, if I'm entirely wrong, accept my apologies.)

You can send h from another instance method on HelloWorld:

class HelloWorld
  def h; puts "hello world!"; end

  def g
    h
  end
end

HelloWorld.new.g
# => "hello world!"

Upvotes: 0

Related Questions