13

If in a ruby file I define a function like so:

def tell_the_truth()
    puts "truth"
end

is there an equivalent to python's main?

if __name__ == "__main__":
    tell_the_truth()

Is it to simply call the function inside the file?

tell_the_truth
Rodrigue
  • 3,617
  • 2
  • 37
  • 49
  • 2
    The reason for the `if` in Python is to prevent the function from being called if the file is included into another one, which your Ruby example doesn't do (as far as I know) – Michael Mrozek Jul 19 '10 at 21:44
  • Thanks Michael. I understand the why behind the if in python. To compare, I have tried putting tell_the_truth() just under the function definition and then importing that file from another ruby file using "require". That prints "truth". So the top level statement seem to be run when a file is imported. – Rodrigue Jul 20 '10 at 08:10

2 Answers2

27

I believe this will work:

if __FILE__ == $0
    tell_the_truth()
end
robert
  • 33,242
  • 8
  • 53
  • 74
2
if __FILE__ == $PROGRAM_NAME
    tell_the_truth()
end
Uladzimir
  • 3,067
  • 36
  • 30