开发者

How to implement a module into a class in Ruby?

I want to implement a module into a class structure.

I do it with simple logic (maybe, you come out with your ideas for the best perfomance):

module Tsito
  class Hello
    def say_hello(name)
      puts "Module > Class: Hello #{name}"
    end
  end
end
tsio = Tsito::Hello.new
tsio.say_hello("Sara")

But, I could i开发者_如何学Pythont. What are your ideas?

class Hello
  module Tsito
    def say_hello(name)
      puts "Class > Module: Hello #{name}"
    end
  end
end
tsio = Hello.new
#tsio.say_hello("Sara") // Gives an error


First, a module has nothing to do with the performance. Its main use is code organization (namespacing) and mixins.

Putting classes under a module is what I used to do, but I haven't tried it vice versa. But it's fully valid.

On your second example, you just put a module inside the class, and expected Ruby to include the module to its parent. But it can't be done. You have to do it manually. Just add include at the end of the line:

class Hello
  module Tsito
    def say_hello(name)
      puts "Class > Module: Hello #{name}"
   end
  end
  include Tsito 
end

Now try

Hello.new.say_hello "hola"

This will work as you expected.

Remember you need to use include wherever you wanted to use the module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜