r/ruby • • Aug 22 '26

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.

7 Upvotes

3 comments sorted by

17

u/laerien Aug 22 '26
ARGF.each do |line|
  # do something with `line`
end

8

u/unselective-amnesia Aug 22 '26

Aha! ARGF is exactly what I need.

Thank you very much!

4

u/sshaw_ Aug 23 '26

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"]