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
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
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
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
?
Vale,
Marvin
On Mar 6, 4:43pm, Brian C. [email protected] wrote:
ruby b.rb
–
Posted viahttp://www.ruby-forum.com/.
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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs