loading...
Cover image for What Are Methods?

What Are Methods?

seanolad profile image Sean ・2 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)

So What Is A Ruby Method?

A method is a concept found in almost all programming languages. Methods are very similar to functions.

Function vs Method

Functions are blocks of code that are interpreted once the function name has been called using the (), which in most languages is the call object/thing(I don't really know what the proper name for it is). A method is the exact same thing as a function except that they're tied to a class or module.

What does that mean?

It means that they only exist inside specific classes and modules. Sometimes a method of the same name is used for different data types(map is a good example for Hashes and Arrays), but internally the code for array.map and hash.map is different.

How and why?

The answer to why is because the data types are different, therefore structured differently, so to get the same outcome for both separate logic must be used. How?, well that's simple, since data types are technically classes you just have to define a function inside of the class and voila!, you're class has a method. This mean that all instances of that class can access the method(assuming that it uses instance variables). Here's a visual:

class Array
  #A bunch of methods above it
  def to_set
    set = {}
    for i in Array
      #some code that adds i to the set
      return set
    end
  end
  #some methods after it
end

#using the method
arr = [1,2,3,3,3] #=> indirectly creating an instance of the Array class
arr = arr.to_set #=> the . tells ruby that you're accessing the class method to_set
#even though we defined to_set like we do a function, since it #was defined inside a class, it's a method
#since our variable is now a set with the same values the output would be
#=> {1,2,3}(remember, sets can't have duplicates)

That's That Folks

Hope you learned something!

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