Skip to content

Instantly share code, notes, and snippets.

@misshie
Last active March 28, 2017 03:25
Show Gist options
  • Save misshie/36be13b72a358ed210a7b48f99a9ad23 to your computer and use it in GitHub Desktop.
Save misshie/36be13b72a358ed210a7b48f99a9ad23 to your computer and use it in GitHub Desktop.
Parse duplicated command-line options into a hash of arrays using Ruby
#!/usr/bin/env ruby
# $ ./klass.rb --hoge=fuga --hoge=puyo --foo=bar
# {:h=>false, :hoge=>["fuga", "puyo"] :foo=>["bar"]}
require 'optparse'
class Klass
attr_reader :opts
def initialize(opts)
@opts = opts
end
def run
p opts
end
end
if $0 == __FILE__
args = Hash.new
ARGV.each do |arg|
match = /--(?<key>.*)=(?<value>.*)/.match(arg)
next unless match
args[match[:key]] = Array.new
args[match[:key]] << match[:value]
end
ARGV.delete_if{|x|/--.*=.*/ =~ x}
opts = ARGV.getopts("h").merge(args)
Klass.new(opts.map{|k,v|[k.to_sym, v]}.to_h).run
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment