Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Method Order in Ruby?

Tags:

ruby

I am new to Ruby. I am familiar with several other languages. My question is about calling methods out of order. For example:

def myfunction
    myfunction2
end

def myfunction2
    puts "in 2"
end

How could I call myfunction2 before it is declared? Several languages let you declare it at the top or in a .h file. How does ruby handle it?

Do I always need to follow this:

def myfunction2
    puts "in 2"
end

def myfunction
    myfunction2
end

Mainly this bugs me when I need to call another method inside of def initialize for a class.

like image 336
Ben Reed Avatar asked May 21 '12 07:05

Ben Reed


People also ask

Does order of methods matter in Ruby?

You could define method in any order, the order doesn't matter anything.

What does .first mean in Ruby?

Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.


1 Answers

You can not call a method before you define it. However, that does not mean you can't define myfunction before myfunction2! Ruby has late binding, so the call to myfunction2 in myfunction will not be associated with the actual myfunction2 before you call myfunction. That means that as long as the first call to myfunction is done after myfunction2 is declared, you should be fine.

So, this is ok:

def myfunction
    myfunction2
end

def myfunction2
    puts "in 2"
end

myfunction

and this is not:

def myfunction
    myfunction2
end

myfunction

def myfunction2
    puts "in 2"
end
like image 55
Idan Arye Avatar answered Oct 04 '22 12:10

Idan Arye