DEV Community

mdiaz564
mdiaz564

Posted on

Class methods vs instance methods, arguments(),return, and constants

1. Calling class methods VS instance methods

If you have a class, and you have defined a class method like,
class Lasagna
def Lasagna.prep_time(layers)
end
end
then, to use that method, you just call
Lasagna.prep_time(4)

If you have a class, but just have a instance method within it like,
class Lasagna
def preparation_time_in_minutes(layers)
end
end
then, to use that method, you first create an instance of the class first
x=Lasagna.new
then, call the method on the instance
x.preparation_time_in_minutes(4)

2. Positional arguments vs keyword arguments

class Calculator
# Positional arguments
def add(num1, num2)
return num1 + num2 # Explicit return
end
# Keyword arguments
def multiply(num1:, num2:)
num1 * num2 # Implicit return
end
end

calc = Calculator.new
calc.add(1, 3)
calc.multiply(num1: 2, num2: 5)

3.Return keyword

If you don't say return while making a method, whatever the last line is in the method will be returned. If you say return, the method will return what you specified.(see example above)

4.Constants

Constants are assigned once and are written in all caps and underscores
MY_FIRST_CONSTANT = 10

Top comments (0)