I am working on my small newbie project. Project consist of two scripts. Script number1 is command line interface which recive parameters from user. Script number 2 creates Cartesian product and write it into text file. My idea is to make everything working without puting evertything into one file). When I try to use ‘load’ I get this error:”
Carthese_product.rb:3:in `<top (required)>': undefined local variable or method
`x_min' for main:Object (NameError)
from D:/Cli_file.rb:25:in `load'
from D:/Cli_file.rb:25:in `<main>'
Script1 (Cli_file.rb):
require 'trollop'
opts = Trollop::options do
banner <<-EOS
Welcome to points generator!
Usage:
test [options] <filenames>+
where [options] are:
EOS
opt :x_min, "Minimal value of X", :type => :int
opt :x_max, "Maximal value of X", :type => :int
opt :y_min, "Minimalna wartosc Y", :type => :int
opt :y_max, "Maksymalna wartosc Y", :type => :int
opt :interval, "Interval between points", :type => :int, :default => 1
opt :products_file, "Name of products_file", :type => :string, :default =>
"Products"
end
a= opts
x_min = a[:x_min]
x_max = a[:x_max]
y_min = a[:y_min]
y_max = a[:y_max]
interval = a[:interval]
products_file = a[:products_file]
load 'Carthese_product.rb'
Script2 (Carthese_product.rb)
products = []
(x_min/interval..x_max/interval).each do |x|
(y_min/interval..y_max/interval).each do|y|
products << [x*interval,y*interval]
end
end
a = products.map.with_index{|w, i| "#{i+1} #{w[0].to_s} #{w[1].to_s} \n"}
aFile = File.new( products_file, "w+")
if aFile
a.each{|x| aFile.write(x)}
else
puts "Something wrong!"
end
I know the easiest sollution is to put everything into one script, but for my educational purposes I want to find another way! Thanks for help & intrest!
You are attempting to use local variables to pass data from one script to the other. It doesn’t work because local variables, when defined at the top level, have file scope and thus cannot be accessed from separate files.
You must create a proper interface to your code so that you can reference it from other scripts. Create a module which implements Cartesian product:
Now,
requirethis file in your command line application executable, use the data given in the command line and write your output:I recommend printing the program’s output to the standard output stream. That way, you can easily redirect the output to a file if you want to: