Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby methods at bottom of script?

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.

like image 304
Jaron Bradley Avatar asked Jul 23 '12 20:07

Jaron Bradley


2 Answers

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
like image 74
steenslag Avatar answered Dec 14 '22 00:12

steenslag


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.

like image 30
André Medeiros Avatar answered Dec 14 '22 00:12

André Medeiros