DEV Community

Cover image for 100 days of coding - Day 3
roxor
roxor

Posted on

100 days of coding - Day 3

Methods

Method or Function?

Don't have a clue what is difference between two of these, but for now most important to learn how they working. Later I will write about differences

In Ruby we will called this methods.

Parentheses?
Ruby is very flexible language. When method expect some results we use parentheses, if not we don't need parentheses. But methods will works in both cases. See example bellow

def something
   puts "Hello World"
end

# this is two valid ways to call the _something_ methods

something  # this is preferred since something methods 
doesn't expect any parameters

something()
Enter fullscreen mode Exit fullscreen mode

However, we prefer to call methods with parentheses in that scenario

def something(name)
  puts "hey" + name
end

something("Ivan") # this is preferred since greet does 
expect parameters

something "Ivan"
Enter fullscreen mode Exit fullscreen mode

We also must make distinction between a variable, parameter and argument.

  • Variables are names who can hold the data.

bottle = water

bottle is variable that hold value "water"

*Parameter * are names that can hold a data in method.
Parameter is placed in parentheses of method.

def something(drink, eat)
    sentence =  "I like to eat " + food + " with a cup of "            
                + drink
    puts sentence
end
Enter fullscreen mode Exit fullscreen mode

Above food and drink are parameters. sentence is a normal variable; it is not a parameter:

Arguments are data that we pass in method when we call the method.

def meal(food, drink)
  sentence =  "I like to eat " + food + " with a cup of " + drink
  puts sentence
end

meal("toast", "coffee") # Here we pass "toast" and "coffee" into our method.
meal("pancakes", "orange juice") # We can also pass "pancakes" and "orange juice" in another call
Enter fullscreen mode Exit fullscreen mode

"toast", "coffe", "pancakes", "orange juice" are arguments

Top comments (0)