Reputation: 113
I have a function that reads in an input test file so that I can do further processing. For some reason it is treating my r as a carriage return \r
def main
#format input
input = []
File.foreach(ARGV[0], 'r') do |f|
puts "f is #{f}"
break
end
end
main()
testfile.csv
149
u,6,3
b,11,11
r,10,11
h,4,8
t,4,5
v,7,9
However whenever an r is encountered in my test file no further output is read in. For some reason r is treated as a carriage return \r
commandline
> ruby bst.rb testfile.csv
f is 149
u,6,3
b,11,11
r
Upvotes: 1
Views: 97
Reputation: 79723
Have a look at the docs for IO.foreach
. The second argument is the separator to use to split up lines, not the open mode for the file (it could also be the limit—the max length string to return).
This means in your call to foreach
you are asking Ruby to return strings from the file separated by the r
character, which is exactly what you are seeing.
The solution is to drop the 'r'
, read only mode is the default so you don’t need it:
File.foreach(ARGV[0]) do |f|
#...
Upvotes: 2
Reputation: 12320
Please try below way
File.foreach("C:/Users/rajarshi.das/Desktop/abc.csv","rb") do |f|
puts "f is #{f}"
break
end
output
>> f is 149
u,6,3
b,11,11
r,10,11
h,4,8
t,4,5
v,7,9
replace r
mode to use rb
mode or r+
mode
File.foreach("C:/Users/rajarshi.das/Desktop/abc.csv","rb")
or
File.foreach("C:/Users/rajarshi.das/Desktop/abc.csv","r+")
Upvotes: 1
Reputation: 26758
I don't know why File.foreach
is splitting on the carriage return nor why it's finding one there. But functionally speaking all you're doing is reading the text of the file, and for that there are alternatives:
puts File.read("test.csv")
# or
File.open("test.csv", "r") { |f| puts f.read }
Upvotes: 0