DEV Community

Cover image for What Are Methods?

Posted on

What Are Methods?

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 and 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
  #some methods after it

#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)
Enter fullscreen mode Exit fullscreen mode

That's That Folks

Hope you learned something!

Top comments (0)