Reputation: 9783
I have this dummy ruby class file (Bar.rb
):
class Bar
foo() # execute foo()
def foo()
puts "Hello world, "
end
end
And I ran the file with:
$ ruby Bar.rb
I was expecting to see "Hello, world" in the command, but got this error:
undefined local variable or method `foo' for Bar:Class (NameError)
from bar.rb:3:in `<main>'
So how do I execute a method? Does Ruby have any main
method (as in Java or C/C++)?
Upvotes: 0
Views: 297
Reputation: 42182
First you define the method, then you call it. No need for a main procedure, the first code outside a class or method will be executed first. The script itself is the main. I'm sure there are better definitions for this, but i'm sure you will underdstand.
def foo()
puts "Hello world, "
end
foo() # execute
Also no need to put this in a class, then you would have to initiate her first.
class Bar
def foo()
puts "Hello world, "
end
end
bar = Bar.new
bar.foo
Upvotes: 1
Reputation: 3509
A couple of reasons this doesn't work as you have written it.
This would work:
class Bar
def self.foo
end
foo
end
As others have said, though, you probably don't need to wrap this in a class.
Upvotes: 1
Reputation: 3036
You don't need any class, you can call any methods you like right from the file itself:
bar.rb:
puts "Hello, world!"
If you want to stick with your code, you are calling foo
before its declaration, which obviously doesn't work.
Upvotes: 1