0

I want to invoke some system commands from a ruby script without having a shell fiddle with things. The catch is that at coding time I don't know how many args there will be.

If I were going through a shell I would build up the command line by concatenation...

I used to do this in perl by passing system and array with however many arguments I wanted. This worked because of the way parameters are passed in perl. Unsurprisingly Ruby does not support that.

Is there a way to do this?

2 Answers 2

6

Put the arguments in an array:

cmd = %w[ls -l -a]

and then splat that array when calling system:

system(*cmd)
# -----^ splat

That's the same as saying:

system('ls', '-l', '-a')

The same syntax is used to accept a variable number of arguments when calling a method:

def variadic_method(*args)
  # This splat leaves all the arguments in the
  # args array
  ...
end
Sign up to request clarification or add additional context in comments.

Comments

0

Is this what you might be referring to? As shown on:

https://ruby-doc.com/docs/ProgrammingRuby/html/tut_methods.html

But what if you want to pass in a variable number of arguments, or want to capture multiple arguments into a single parameter? Placing an asterisk before the name of the parameter after the ``normal'' parameters does just that.

def varargs(arg1, *rest) "Got #{arg1} and #{rest.join(', ')}" end

varargs("one") » "Got one and "

varargs("one", "two") » "Got one and two"

varargs "one", "two", "three" » "Got one and two, three"

In this example, the first argument is assigned to the first method parameter as usual. However, the next parameter is prefixed with an asterisk, so all the remaining arguments are bundled into a new Array, which is then assigned to that parameter.>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.