46

I'm new to Ruby, so apologies if this sounds really silly.

I can't seem to figure out how to write a "main" code and have methods in the same file (similar to C). I end up with a "main" file which loads a seperate file that has all the methods. I appreciate any guidance on this.

I spotted the following SO post but I don't understand it: Should I define a main method in my ruby scripts?

While it's not a big deal, it's just easier being able to see all the relevant code in the same file. Thank you.

[-EDIT-]

Thanks to everyone who responded - turns out you just need to define all the methods above the code. An example is below:

def callTest1
    puts "in test 1"
end

def callTest2
    puts "in test 2" 
end

callTest1
callTest2

I think this makes sense as Ruby needs to know all methods beforehand. This is unlike C where there is a header file which clearly list the available functions and therefore, can define them beneath the main() function

Again, thanks to everyone who responded.

Community
  • 1
  • 1
rchn
  • 973
  • 1
  • 8
  • 10
  • Your answer looks better than the others to me, why don't you post it as an answer and accept it (that's better than in an edit) – barlop Jun 28 '15 at 04:12

6 Answers6

45

@Hauleth's answer is correct: there is no main method or structure in Ruby. I just want to provide a slightly different view here along with some explanation.

When you execute ruby somefile.rb, Ruby executes all of the code in somefile.rb. So if you have a very small project and want it to be self-contained in a single file, there's absolutely nothing wrong with doing something like this:

# somefile.rb

class MyClass
  def say_hello
    puts "Hello World"
  end
end

def another_hello
  puts "Hello World (from a method)"
end

c = MyClass.new
c.say_hello
another_hello

It's not that the first two blocks aren't executed, it's just that you don't see the effects until you actually use the corresponding class/method.

The if __FILE__ == $0 bit is just a way to block off code that you only want to run if this file is being run directly from the command line. __FILE__ is the name of the current file, $0 is the command that was executed by the shell (though it's smart enough to drop the ruby), so comparing the two tells you precisely that: is this the file that was executed from the command line? This is sometimes done by coders who want to define a class/module in a file and also provide a command-line utility that uses it. IMHO that's not very good project structure, but just like anything there are use cases where doing it makes perfect sense.

If you want to be able to execute your code directly, you can add a shebang line

#!/usr/bin/env ruby

# rest of somefile.rb

and make it executable with chmod +x somefile.rb (optionally rename it without the .rb extension). This doesn't really change your situation. The if __FILE__ == $0 still works and still probably isn't necessary.

Edit

As @steenslag correctly points out, the top-level scope in Ruby is an Object called main. It has slightly funky behavior, though:

irb
>> self
=> main
>> self.class
=> Object
>> main
NameError: undefined local variable or method `main' for main:Object
from (irb):8

Don't worry about this until you start to dig much deeper into the language. If you do want to learn lots more about this kind of stuff, Metaprogramming Ruby is a great read :)

dantswain
  • 5,427
  • 1
  • 29
  • 37
29

No there isn't such structure. Of course you can define main function but it won't be called until you do so. Ruby execute line by line so if you want to print 'Hello World' you simply write:

puts 'Hello World'

The question that you mentioned is about using one file as module and executable, so if you write

if __FILE__ == $0
  # your code
end

It will be called only if you run this file. If you only require it in other file then this code will never run. But IMHO it's bad idea, better option is using RubyGems and there add executables.

Hauleth
  • 22,873
  • 4
  • 61
  • 112
  • 4
    If you want to stick to `rubocop` style guide, the recommended way is `$PROGRAM_NAME == __FILE__` (so replace `$0` with `$PROGRAM_NAME` and reverse the left with the right operand). More info is available here https://github.com/github/rubocop-github/blob/master/STYLEGUIDE.md – Nikolaos Georgiou Sep 08 '18 at 15:00
6

Actually there is a main, but it is not a method; it's the top-level object that is the initial execution context of a Ruby program.

class Foo
  p self
end
#=> Foo

p self
#=> main

def foo 
  p self
end
foo
#=> main
steenslag
  • 79,051
  • 16
  • 138
  • 171
1

There is no magic main function in Ruby. See http://en.wikipedia.org/wiki/Main_function#Ruby

Alexander
  • 9,737
  • 4
  • 53
  • 59
1

If you wish to run Ruby scripts like C compiled files, do the following:

#!/usr/bin/env ruby
puts "Hello"

and then chmod a+x file_name.rb. Everything that is below the first line will be run, as if it was contents of main in C. Of course class and function definitions won't give you any results until they are instantiated/invoked (although the code inside class definitions is actually evaluated, so you could get some output but this is not expected in normal circumstances).

Aleksander Pohl
  • 1,675
  • 10
  • 14
0

Another way to write main() method is:

class HelloWorld
    def initialize(name)
        @name = name
    end

    def sayHello()
        print "Hello #@name!"
    end
end

def main()
    helloWorld = HelloWorld.new("Alice")
    helloWorld.sayHello
end

main


pcsutar
  • 1,715
  • 2
  • 9
  • 14