Skip to content

Instantly share code, notes, and snippets.

@kaecy
Last active December 31, 2015 18:59
Show Gist options
  • Select an option

  • Save kaecy/8031022 to your computer and use it in GitHub Desktop.

Select an option

Save kaecy/8031022 to your computer and use it in GitHub Desktop.
simple forward-slash argument analyser and simple calc program using it with demo output
> calc //debug /o 1 1 /a sum
O ----
1
1
A ----
sum
2
module Args
def self.analyse args
error, r = nil, {}
flag, flags = nil, [];
args.each_with_index do |arg, index|
if index == 0
if ! (arg =~ /^\/.$|^\/\/../)
break error = true;
end
end
if arg =~ /^\/.$|^\/\/../
if index != 0 && r[flag].empty?
r[flag] = nil;
end
flag = arg.sub(/\/{1,2}/, '');
flags.push flag;
r.store flag, [];
else
r[flag].push arg;
end
end
if ! error && flag != nil
if r[flag].empty?
r[flag] = nil;
end
r.store "flags", flags;
r;
else
nil
end
end
end
args = Args.analyse(ARGV);
if ! args.nil?
case args['flags'][0]
when "debug"
args.delete "flags";
args.delete "debug";
args.each do |flag, values|
puts "#{flag.upcase} ----", values, "\n";
end
when"inspect"
puts args.inspect;
end
end
require "args";
def action op, nums
ans = 0;
case op
when "sum"
nums.each do |num|
ans += num.to_i;
end
when "mul"
ans = nums.shift.to_i;
nums.each do |num|
ans *= num.to_i;
end
end
ans;
end
def check a, o
if ! a.nil? && ! o.nil?
if a.length == 1 && o.length > 0
0;
end
else
nil
end
end
def commLineError
puts "command line error";
exit false;
end
def syntaxError
puts "syntax error";
exit false;
end
## PROGRAM #####################################################################
args = Args.analyse(ARGV);
commLineError unless args
syntaxError unless check(args['a'], args['o'])
print \
action(
args['a'][0],
args['o']
), "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment