Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extend a module and also directly reference its methods in Ruby

I have the following code

module Hello
    def hello_world
        puts "Hello World"
    end
end

class Test
    extend Hello
end

test = Test
test.hello_world
Hello.hello_world

and this has the following output

Hello World
main.rb:13:in `<main>': undefined method `hello_world' for Hello:Module (NoMethodError)

How do I get the code above to work so that both test.hello_world and Hello.hello_world work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Hello doesn’t respond to hello_world because hello_world is not a class method. You can get the desired behavior by extending the Hello module with self like this:

module Hello
  extend self

  def hello_world
    puts "Hello World"
  end
end

class Test
  extend Hello
end

test = Test
test.hello_world  #=> Hello World
Hello.hello_world #=> Hello World
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading