user1508893
user1508893

Reputation: 9783

execute a method in a ruby file

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

Answers (3)

peter
peter

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

Rich Drummond
Rich Drummond

Reputation: 3509

A couple of reasons this doesn't work as you have written it.

  1. The method foo hasn't been declared before you attempt to call it.
  2. The method foo, as you have declared it, is an instance method. You're not invoking it on an instance of the class.

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

Anton
Anton

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

Related Questions