I'm using ruby 1.8.7. I could have sworn that I've written my functions at the bottom of my script before and it worked fine.
Do I have to put them at the top? It seems to be the only way they work now. Not a big deal. I just prefer to have them at the bottom so I figured I'd ask.
You can do initializing code in one or more BEGIN-blocks (inherited from Perl, which inherited them from awk).
can_i_do_this? #=>yes
BEGIN {
def can_i_do_this?
puts "yes"
end
}
And for completeness, there are also END-blocks:
END {
can_i_do_this? #=> yes
}
def can_i_do_this?
puts "yes"
end
a
def a
puts "Hello world!"
end
Running this script in Ruby will give you:
script.rb:1:in `<main>': undefined local variable or method `a' for main:Object (NameError)
So no, you can't have them at the bottom. As Ruby is an interpreted language, any code is parsed and processed at runtime ONLY. Therefore, you can only run code (call methods, use variables...) that have already been defined prior to the actual reference.
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