Undefined method - why?

I’m getting “undefined method” for a method I’ve defined, in line 5 of main.cr, where foo() is being called. I’ve looked at real Crystal programs written by people who know what they’re doing, re-read the language reference GitBook, and googled. I’m missing some syntax detail with my swiss-cheese C++ rotted brain!

In file alpha.cr:

module LotsaStuff
   def foo(x)
       x*x
   end #def
end #module

In file main.cr, the main program:

require "./alpha.cr"
module LotsaStuff
    puts "Starting!"
    z = foo(10)            <=== Error: undefined method
    puts z
end #module

Try with def self.foo(...) (add self. to make it a module method)

1 Like

Ah! It works!! IT’S ALIVE!!!

Problem solved. Thank you!

The odd little details I read about but don’t absorb…

It’s as if ‘module’ were ‘class’ in a way. What my python-addled creaky old rust-trap brain thinks is a global function (or variable or some other thing) is really a member of a “class” that’s called a module, and I sortof have to pretend I’m doing Python where you put “self.” in certain places (lots of places in actual Python.)

If you feel more comfortable, there’s a common Ruby pattern usable in Crystal:

class MyClass
  module ClassMethods
    def foo(x)
      x * x
    end
  end

  extend ClassMethods
end

puts MyClass.foo 2

Here using extend will use the instance method of ClassMethods module in MyClass

1 Like