Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Unix pager programs like `less` from Ruby?

Tags:

unix

ruby

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?

like image 964
Ankit Avatar asked Mar 09 '12 15:03

Ankit


3 Answers

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

like image 50
user1252434 Avatar answered Oct 04 '22 03:10

user1252434


A simple hack:

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

system("less #{f.path}")
like image 25
Limbo Peng Avatar answered Oct 04 '22 04:10

Limbo Peng


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

like image 21
microspino Avatar answered Oct 04 '22 05:10

microspino