DEV Community

Cover image for Intro To Ruby Modules
Sean
Sean

Posted on

3 1

Intro To Ruby Modules

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!😎

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay