开发者

Why can't I call a method?

开发者 https://www.devze.com 2023-02-16 02:34 出处:网络
So I thought I\'d learn some Ruby. I was playing with the interprete开发者_StackOverflow中文版r but I wanted to make bigger programs so I downloaded Aptana, an IDE. When I try to run this code:

So I thought I'd learn some Ruby. I was playing with the interprete开发者_StackOverflow中文版r 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?


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


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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消