How to use Unix pager programs such as `less` from Ruby?

Suppose I have a line under the name very_long_stringwhose contents I want to send to standard output. But since the line is very long, I want to use lessto display text on the terminal. When i use

`less #{very_long_string}`

I get an error File not foundand if I use:

`less <<< #{very_long_string}`

I get an error message unexpected redirection.

So how to use lessRuby from the inside?

+5
source share
3 answers

You can open a channel and pass your line less through your stdin.

IO.popen("less", "w") { |f| f.puts very_long_string }

(Assuming very_long_string is a variable containing your string.)

: http://www.ruby-doc.org/core-1.8.7/IO.html#method-c-popen

+15

less , . , :

shell-command-1 | shell-command-2 | shell-command-3 | less

:

echo tanto va la gatta al lardo che ci lascia lo zampino|less

.. , irb:

`echo tanto va la gatta al lardo che ci lascia lo zampino|less`

:

your_string = "tanto va la gatta al lardo che ci lascia lo zampino"
`echo "#{your_string}"|less`

, SO.

. : https://gist.github.com/4069

+1

Simple hack:

require 'tempfile'
f = Tempfile.new('less')
f.write(long_string)

system("less #{f.path}")
0
source

All Articles