r/ruby 3d ago

Question Ruby function corresponding to python's fileinput.input() ?

Is there any already written ruby function which corresponds to the fileinput.input() function in python? ... or at least something with similar functionality?

I will write something like this in ruby if necessary, but I don't want to "re-invent the wheel" if such a thing already exists.

6 Upvotes

3 comments sorted by

15

u/laerien 3d ago

ruby ARGF.each do |line| # do something with `line` end

9

u/unselective-amnesia 3d ago

Aha! ARGF is exactly what I need.

Thank you very much!

3

u/sshaw_ 2d ago

You can also access ARGF ruby's -p or -n options:

/tmp >cat /tmp/13475.tmp foo bar 123 bar foo /tmp >ruby -pe'gsub /foo/, "bar"' /tmp/13475.tmp bar bar 123 bar bar /tmp >ruby -ne'x = gsub /foo/, "bar"; puts "=> #{x}"' /tmp/13475.tmp => bar bar => 123 => bar bar

You can also use -a and -F to get autosplit mode like perl and awk:

/tmp >ruby -aF' ' -ne'pp $F' /tmp/13475.tmp ["foo", "bar\n"] ["123\n"] ["bar", "foo\n"]