LoginSignup
1
1

More than 5 years have passed since last update.

Rubyで外部コマンドに渡すフラグをRubyっぽくメソッドに渡す

Posted at

Rubyから外部コマンドを呼ぶときに-fooのようなフラグと-bar 0のような引数をとるものが混在したときにどうRubyで表すかという問題です。

結論としては

def baz *args
  arr = []
  hash = { }
  args.each do |e|
    if e.instance_of? Hash
      hash.update e
    else
      arr << e
    end
  end
  options = ""
  hash.each{|k,v| options += "-#{k} #{v} "}
  arr.each{|e| options += "-#{e}"}

  system "command #{options}"
end

baz :foo, bar: 0

のように可変長引数で受ければ両者がごちゃまぜになったものを受け取れるのでそれを整理して整形してあげます。

用途によっては整理と整形を分けずにそのまま文字列化してもいいでしょう。

ちなみに先に引数なしのフラグ、後に引数ありのフラグの順じゃないとArgumentErrorになるようです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1