Method: Shellwords#parse

Defined in:
lib/standard/facets/shellwords.rb

#parse(argv, opts) ⇒ Object (private)

The coolest little arguments parser in all of Rubyland.

CREDIT: Michel Martens



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/standard/facets/shellwords.rb', line 37

def parse(argv, opts)
  argv = (String === argv ? shellwords(argv) : argv.to_a.dup)
  args = []
  while argv.any?
    item = argv.shift
    flag = opts[item]
    if flag
      # Work around lambda semantics in 1.8.7.
      arity = [flag.arity, 0].max
      # Raise if there are not enough parameters
      # available for the flag.
      if argv.size < arity
        raise ArgumentError
      end
      # Call the lambda with N items from argv,
      # where N is the lambda's arity.
      flag.call(*argv.shift(arity))
    else
      # Collect the items that don't correspond to
      # flags.
      args << item
    end
  end
  args
end