3 ms·
Interesting, so it's reading text from STDIN into an Array, then executing its arguments as Ruby code in the context of that Array (or if you pass -l, in the co
by Ajedi32 8y ago
Interesting, so it's reading text from STDIN into an Array, then executing its arguments as Ruby code in the context of that Array (or if you pass -l, in the context of each line individually). So all the standard methods on the [Array][1] (or [String][2]) class become accessible as top-level methods.
A few examples:
Capitalizing a line:
echo hello world | rb -l capitalize
Printing only unique lines:
printf 'hello\nworld\nhello\n' | rb uniq
Computing the sum of numbers in a table:
printf '1\n2\n3\n' | rb 'map(&:to_i).sum'
Personally I think it's a really cool idea.
[1]: https://ruby-doc.org/core/Array.html https://ruby-doc.org/core/Array.html
[2]: https://ruby-doc.org/core/String.html https://ruby-doc.org/core/String.html
- star-techate 8y agoecho hello world | ruby -pe '$_.capitalize!' printf 'hello\nworld\nhello\n' | ruby -le 'puts STDIN.to_a.uniq ps | ruby -lane 'BEGIN { b = 0 }; b += $F[0].to_i; END { print "sum of PIDs: #{b}" } select whatever column you want, to sum up. Really what Ruby needs is a flag that adds some capabilities to NilClass, so that these BEGIN blocks aren't needed.
- ricardobeat 8y agoIf this was an attempt at showing this tool is unnecessary, you just did the opposite. Each of your examples use different flags, inputs and print methods. The last is particularly good at proving the point!
- ashelmire 8y agoEach of those examples is doing different things. This rb script locks you into two of the options.
- dragonwriter 8y ago> Really what Ruby needs is a flag that adds some capabilities to NilClass, so that these BEGIN blocks aren't needed. Does it, though? ps | ruby -le 'b = $<.reduce(0) {|s, l| s + l.split(0).to_i}; print "sum of PIDs: #{b}"' or: ps | ruby -lane 'b = (b || 0) + $F[0].to_i; END { print "sum of PIDs: #{b}" }'