-1

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'.

sawa
  • 165,429
  • 45
  • 277
  • 381
the_lrner
  • 575
  • 1
  • 5
  • 11

1 Answers1

0

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)
spickermann
  • 100,941
  • 9
  • 101
  • 131