10

Reading the ruby docs isn't overly helpful here:

Returns true if ios is associated with a terminal device (tty), false otherwise.

I was hoping to get some additional resources or explanation to help me understand this better.

For context, I'm writing a little command line program that accepts either a file path or piped content into the ruby executable and am using #tty? to determine what is coming in.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
daino3
  • 4,386
  • 37
  • 48
  • 1
    Even when invoked from a console (= tty), your script might still have to read a file, right? I suggest you use the passed argument as file path and if no arguments are passed read from `$stdin`. Even better, use two named arguments where one is parameterized with the file name and the other specifies that input is to be read form `$stdin`. – Raffael Jun 25 '16 at 20:01

2 Answers2

10

Seems like http://www.jstorimer.com/blogs/workingwithcode/7766125-writing-ruby-scripts-that-respect-pipelines supplies the most concise description of what #tty? does:

Ruby's IO#isatty method (aliased as IO#tty?) will tell you whether or not the IO in question is attached to a terminal. Calling it on $stdout, for instance, when it's being piped will return false.

Here is some relevant info that you may find useful:

Background meaning via What do pty and tty mean?:

In UNIX, /dev/tty* is any device that acts like a "teletype", ie, terminal. (Called teletype because that's what we had for terminals in those benighted days.)

In the spirit of the question, here's an example of writing to /dev/tty from http://zetcode.com/lang/rubytutorial/io/:

#!/usr/bin/ruby

fd = IO.sysopen "/dev/tty", "w"
ios = IO.new(fd, "w")
ios.puts "ZetCode"
ios.close
Community
  • 1
  • 1
SoAwesomeMan
  • 3,226
  • 1
  • 22
  • 25
  • 3
    Thanks, @SoAwesomeMan. Exactly what I wanted - additional resources with some explanation. – daino3 Jun 26 '16 at 17:23
1

Look at how grep handles this situation for the traditional UNIX approach: No file specified? Default to $stdin and don't worry about TTY status, maybe someone wants to paste into the terminal. If a filename is specified, read from that and ignore STDIN.

The tty? function is there so you can know if you should send things like ANSI escape codes to colour your output. It's not generally a reliable signal of if someone wants to supply input over STDIN.

tadman
  • 208,517
  • 23
  • 234
  • 262