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.
You could define method in any order, the order doesn't matter anything.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With