Verhogen
Verhogen

Reputation: 28621

Ruby Switch Between File and Standard Input

How would you create a variable that could be read. It would read from a certain file if it exists, otherwise it would read from standard input. Something like:

input = File.open("file.txt") || in

This doesn't work, but I think this should be done pretty often, but I can't find a nice way to do it.

Upvotes: 3

Views: 2453

Answers (3)

Andrew Grimm
Andrew Grimm

Reputation: 81520

I think ruby has the ability to treat arguments that aren't used before STDIN is first used as if it were filenames for files piped into standard input.

Upvotes: 1

Simone Carletti
Simone Carletti

Reputation: 176412

This this works for you?

input = File.exist?("file.txt") ? File.open("file.txt") : STDIN

Upvotes: 4

Related Questions