[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Nuby question regarding classes and ARGV

Jano Svitok

12/22/2006 6:01:00 PM

On 12/22/06, Jason Mayer <slamboy@gmail.com> wrote:
> I just took a program that works using a command line argument and turned it
> into a class so that I could require it from . Anyway, I was just wondering
> how you would pass somethign to it now as an argument.
>
> if the syntax of the original program was 'ruby program.rb Jason' and the
> program did stuff with 'Jason', how would I go about making another program
> (a GUI for example) pass along information into that program as an
> argument? I can't seem to get this to work. I've tried variants of the
> following:
> psuedo code (saved as program2.rb):
> 'require program.rb'
> b = 'Jason'
> a = ClassNameInProgram.new(b)
> a = ClassNameInProgram.new {b}
> a = ClassNameInProgram.new b
>
> If I run 'ruby program2.rb Jason', I get the same output as if I'd run '
> program.rb Jason'. What am I not doing correctly? Hopefully I've explained
> this adequately and hopefully I'm not being incredibly stupid.

1. if you have

class ClassName...
def initialize
...ARGV[0]...
end
end

turn it into

class ClassName....
def initialize(*argv)
....argv[0]...
end
end

or

class ClassName....
def initialize(arg0, arg1, arg2)
....arg0...
end
end

2. you can have both varieties:

do the above changes and
at the very end of the file put the following:

if __FILE__ == $0
ClassName...new(*ARGV)
end

---
Notes:
A bit safer way is to write
if File.expand(__FILE__) == File.expand($0)
to handle program.rb vs ./program.rb cases

*ARGV "expands" the ARGV array as the actual parameters to new.
I.e. it is the same as calling new(ARGV[0], ARGV[1],...) It's a handy trick,
that can be used in case statements as well. (arr = [1,2,3], ... when *arr)

3. In the case of wrapping a script I usually split the code into
initialization (new/initialize) and actual processing
(run/process/whatever).