Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a public method in a Ruby module?

Tags:

ruby

I must be making a n00b mistake here. I've written the following Ruby code:

module Foo
   def bar(number)
      return number.to_s()
   end
end
puts Foo.bar(1)

test.rb:6:in <main>': undefined methodbar' for Foo:Module (NoMethodError)

I wish to define a single method on a module called Foo.bar. However, when I try to run the code, I get an undefined method error. What am I doing wrong?

like image 340
Vivian River Avatar asked Apr 24 '13 01:04

Vivian River


People also ask

How do you call a method in a module in Ruby?

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.

Can Ruby modules have private methods?

Private instance/class methods for modulesDefining a private instance method in a module works just like in a class, you use the private keyword. You can define private class methods using the private_class_method method.


2 Answers

You could do with:

module Foo
   def self.bar(number)
      number.to_s
   end
end
puts Foo.bar(1)
like image 104
xdazz Avatar answered Sep 27 '22 21:09

xdazz


Every module in Ruby can be mixed in an object. Once a class is an object, you could mix the methods in a class using the word extend:

module Foo
  def bar
    'bar'
  end
end

class MyInstanceMethods
   include Foo
end

class MyClassMethods
   extend Foo
end

## Usage:
MyInstanceMethods.new.bar
=> "bar"

MyClassMethods.bar
=> "bar"

If you wish calling the bar method directly from the Foo module, you could do in the same way @xdazz wrote, but since the extend word mixes to a Class:

MyInstanceMethods.class
=> Class

MyClassMethods.class
=> Class

Module.class
=> Class # Hey, module is also a class!!!!!

The trick:

module Foo
  extend self # self of Foo is the Module!

  def bar
    # .....
  end
end

Now you can see Foo.bar returning the expected result :P

like image 37
leandronsp Avatar answered Sep 27 '22 20:09

leandronsp