#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2014
    Posts
    1
    Rep Power
    0

    Undefined Local Variable or Method


    Today, I started to try to learn ruby. When I went to make my first method, I kept receiving an error "undefined local variable or method."

    I tried looking up how to make methods in Ruby online, so that I would be sure its not my own fault. I copy pasted several examples into my ide, all of which returned the same error.

    I made a simple method (below) and I get the same error: <class:TEST>': undefined local variable or method `greeter' for TEST:Class (NameError)

    Code:
    class TEST
    
      def greeter()
        puts 'Hi'
      end
      greeter
    
    end
    The built in ruby methods work fine. Is there something wrong with what I'm doing?
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,926
    Rep Power
    1045
    Hi,

    I think there's a general misunderstanding with regard to object-oriented programming.

    The methods you define within a class belong to the instances of this class, not the class itself. So when you create a TEST object, this object will have a greeter method:

    ruby Code:
    class Test
     
      def greeter()
        puts 'Hi'
      end
     
    end
     
    # now instantiate the class
    test = Test.new
     
    # this object has a greeter() method
    test.greeter()

    It works just like in other object-oriented languages like Java, C++, whatever.

    If you want to add a method to the class itself, that's very different. You now have to define a so called “singleton method” for the class object:

    ruby Code:
    class Test
     
      # define a singleton method for the Test class object
      # instead of hard-coding the "Test", you could also write "self"
      def Test.class_greeter()
        puts 'The class says Hi.'
      end
     
    end
     
    # the Test class has a class_greeter() method
    Test.class_greeter()

    Most other languages don't have this concept of singleton methods. They use a special keyword named "static" instead.
    The 6 worst sins of securityHow to (properly) access a MySQL database with PHP

    Why can’t I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".

IMN logo majestic logo threadwatch logo seochat tools logo