top | item 42570827

(no title)

ryanmjacobs | 1 year ago

FYI, one of my favorite Ruby idioms is to capture command output with `open(...){_1.read}`

  pp open("|ls -lh /usr/bin/ls"){_1.read}
  "-rwxr-xr-x 1 root root 135K Aug 30 04:57 /usr/bin/ls\n"
or to quickly print tabular data

  open("|column -t -s \\t", "w"){_1 << tsv_data}

discuss

order

vidarh|1 year ago

Am I missing something - it's 2am here, so possibly - or could you not just use backticks for the first one?

ryanmjacobs|1 year ago

Oh that's embarrassing -- you're right, the first example doesn't make sense. Kinda pointless actually haha

I use it for code like this:

  raw = IO.popen(%W[gzip -d -c -- #{path}]){_1.read}
  raw = IO.popen(%W[gzip -d -c], in: pipe){_1.read}
  raw = IO.popen(%W[git status --porcelain -- #{path}]){_1.read}
Useful because it eliminates /bin/sh footguns (e.g. `md5sum hello&world` forking or `~john` expanding), plus you get kernel.spawn() options. `open("| ...)` only made sense for the second example.

Anyway, I find "_1" more eye-pleasing than:

  IO.popen(%W[gzip -d -c #{path}]){|io| io.read}