Search code examples
rubyrubymine

Defining a method in Rubymine returns "undefined method" error


I am executing a class with only this code in rubymine:

def saythis(x)
  puts x
end
saythis('words')

It returns an error: undefined method `saythis', rather than printing the string 'words'. What am I missing here? Replicating this code in irb prints the string 'words'.


Solution

  • I assume you wrote a class like the one below and did not write that code into a irb console. The problem is that you define an instance method, but try to call the method from the class level.

    class Foo
      def say_this(x)      # <= defines an instance method
        puts x
      end
      say_this('words')    # <= calls a class method
    end
    

    There a two ways to "fix" this:

    1. Define a class method instead of an instance method: def self.say_this(x)
    2. Call the instance method instead of the class method call: new.say_this(x)