ruby script

M

Mlle

Hi,

I wrote a ruby script but I'd like to define a method within it and
call the method from the main method. How do I do that? Do I have to
define the whole file as a module or something?
Thanks
 
B

Brian Candler

Mlle wrote in post #985808:
I wrote a ruby script but I'd like to define a method within it and
call the method from the main method. How do I do that? Do I have to
define the whole file as a module or something?

Nope (although using modules can make your code easier to reuse and/or
combine with other code)

Simple example which I think achieves what you want:

---- a.rb ----
def say_hello
puts "Hello, world!"
end

---- b.rb ----
require 'a'
say_hello

---- command line ----
ruby b.rb
 
Q

Quintus

Am 06.03.2011 21:45, schrieb Mlle:
Hi,

I wrote a ruby script but I'd like to define a method within it and
call the method from the main method. How do I do that? Do I have to
define the whole file as a module or something?
Thanks

Ruby doesn't have a main method. Your script starts being executed at
the very top and ends at the very bottom. Everything in between is
executed line by line.

How about:

====================
def mymethod
puts "Hello from my method!"
end

mymethod
====================

?

Vale,
Marvin
 
M

Mlle

Mlle wrote in post #985808:


Nope (although using modules can make your code easier to reuse and/or
combine with other code)

Simple example which I think achieves what you want:

---- a.rb ----
def say_hello
  puts "Hello, world!"
end

---- b.rb ----
require 'a'
say_hello

---- command line ----
ruby b.rb

I realized I was having issues because I defined the method I wanted
to use after the script...obviously it should be defined before. Then
it runs just fine without having to be a module.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top