DEV Community

loading...
Cover image for Intro To Ruby Modules

Intro To Ruby Modules

seanolad profile image Sean ・1 min read

What are modules?

Ruby modules are similar to ruby classes. They're large groups of methods that fall under a category. So an example of a built in ruby module would be the Math module.

Module Us?

We can create our own custom modules using the current ruby module syntax. It looks like this:

module Somename
#loads of methods in-between.
end
Enter fullscreen mode Exit fullscreen mode

How can I use modules?

Simple repeatable tasks are great for modules. If there's something you're going to use over and over I recommend creating a module to add it to it.

Let's See some Code! 🐱‍💻


module Greeting
  def hi
    puts "Hi!"
  end
  def hello
    puts "hello"
  end
  def gmorning
    puts "Good Morning"
  end
  def hola 
    puts "hola"
  end
end
greet = include Greeting
greet.gmorning #=> Good Morning
greet.hello #=> hello
greet.hola #=> hola
greet.hi #=> Hi!
Enter fullscreen mode Exit fullscreen mode

In the code, the module, Greeting, has 4 methods: gmorning, hello, hi, and hola. The keyword, include, allows the module and it's method to be used. The variable greet, is an instance of Greeting, and can access all of it's methods. So, once we do, greet.hi the output will be: Hi!.

You sure it works?

Here's the code, run it and see what happens.

Go write some code!!😃

Hope you learned somehting!😎

Discussion (0)

pic
Editor guide