Reputation: 10063
Question: Is there a simple way to print out an array in Ruby with elements separated by spaces?
Details:
I want to use Ruby to Benchmark commands and run the command. Something like:
script.rb ./command_name arg1 arg2 arg3 ...
For example:
script.rb ls -lh
should run ls -lh
. I tried to do this with:
require 'benchmark'
puts Benchmark.measure{system(ARGV.to_s)}
(note ignore benchmark for this question I just included that because that what I'm using this for) but that does not work because ARGV gets printed without spaces. For example ls -lh
becomes ls-lh
. Obviously I could create my own string by parsing the ARGV array and inserting spaces between elements in loop. But I assume there is a more elegant Ruby solution but I haven't been able to figure one out yet so I'm wondering if anyone has suggestions.
Upvotes: 3
Views: 4041
Reputation: 159105
[Update]
You should use l0b0's answer
[Original answer]
You can easily join elements of an Array together with join
. ARGV is an Array.
ARGV.join(" ")
Upvotes: 7
Reputation: 58808
To produce a reusable argument string:
ARGV.map{|arg| Shellwords.escape arg}.join(' ')
Upvotes: 4