Home > Software engineering >  How to extend a module and also directly reference its methods in Ruby
How to extend a module and also directly reference its methods in Ruby

Time:03-11

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?

CodePudding user response:

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
  •  Tags:  
  • ruby
  • Related