loading...
Cover image for Intro To Ruby Modules

Intro To Ruby Modules

seanolad profile image Sean ・1 min read

Beginners Ruby Method Guide (9 Part Series)

1) How to use the Ruby minmax_by Method 2) How to Remove Duplicates from Arrays 3 ... 7 3) How To Use The Map Method In Ruby 4) How To Use A Hash 5) Ruby Classes 6) What Are Methods? 7) Creating a unique password generator using Ruby 8) Intro To Ruby Modules 9) Intro To Ruby Procs and Lambdas(and the difference)

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

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!

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

Beginners Ruby Method Guide (9 Part Series)

1) How to use the Ruby minmax_by Method 2) How to Remove Duplicates from Arrays 3 ... 7 3) How To Use The Map Method In Ruby 4) How To Use A Hash 5) Ruby Classes 6) What Are Methods? 7) Creating a unique password generator using Ruby 8) Intro To Ruby Modules 9) Intro To Ruby Procs and Lambdas(and the difference)

Posted on by:

seanolad profile

Sean

@seanolad

Hi, name's Sean. I'm a junior developer(still in high school though).

Discussion

markdown guide