Suppose I have a string called very_long_string
whose content I want to send to the standard output. But since the string is very long, I want to use less
to display the text on the terminal. When I use
`less #{very_long_string}`
I get File not found
error message, and if I use:
`less <<< #{very_long_string}`
I get unexpected redirection
error message.
So, how to use less
from inside Ruby?
You could open a pipe and feed your string to less via its stdin.
IO.popen("less", "w") { |f| f.puts very_long_string }
(Assuming very_long_string is the variable holding your string.)
See: http://www.ruby-doc.org/core-1.8.7/IO.html#method-c-popen
A simple hack:
require 'tempfile'
f = Tempfile.new('less')
f.write(long_string)
system("less #{f.path}")
Although less
can read text files its natural fit is to use it as the last command in a pipe. So a natural fit would be:
shell-command-1 | shell-command-2 | shell-command-3 | less
At your shell prompt:
echo tanto va la gatta al lardo che ci lascia lo zampino|less
..So you can try this in irb:
`echo tanto va la gatta al lardo che ci lascia lo zampino|less`
but I will prefer to use:
your_string = "tanto va la gatta al lardo che ci lascia lo zampino"
`echo "#{your_string}"|less`
If you have time read this SO question.
For a thorough demonstration of using system calls in ruby see this gist: https://gist.github.com/4069
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With