Home > Software engineering >  Open file with write throws "No implicit conversion of String into Integer"
Open file with write throws "No implicit conversion of String into Integer"

Time:12-16

It's been quite a while time since I last wrote code in Ruby (Ruby 2 was new and wow it's 3 already), so I feel like an idiot.

I have a text file containing only the word:

hello

My ruby file contains the following code:

content = File.read("test_file_str.txt","w")
puts content

When I run it, I get:

`read': no implicit conversion of String into Integer (TypeError)

I've never had this happen before, but it has been quite a while since I wrote code, so clearly PEBKAC.

However, when I run this without ,"w" all is seemingly well. What am I doing wrong?

ruby 3.0.3p157 (2021-11-24 revision 3fb7d2cadc) [x64-mingw32]

CodePudding user response:

As per the docs, the second argument for File.read is the length of bytes to be read from the given file which is meant to be an integer.

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.

So, in your case the error happens because you're passing an argument which must be an integer. It doesn't state this per-se in the docs for File.read, but it does it for File#read:

Reads length bytes from the I/O stream.

length must be a non-negative integer or nil.

If you want to specify the mode, you can use the mode option for that:

File.read("filename", mode: "r") # "r" or any other
# or
File.new("filename", mode: "r").read(1)

CodePudding user response:

Open Files for Reading Don't Accept Write Mode

In general, it doesn't make sense to open a filehandle for reading in write mode. So, you need to refactor your method to something like:

content = File.read("test_file_str.txt")

or perhaps:

content = File.new("test_file_str.txt", "r ").read

depending on exactly what you're trying to do.

See Also: File Permissions in IO#new

The documentation for File in Ruby 3.0.3 points you to IO#new for the available mode permissions. You might take a look there if you don't see exactly the options you're looking for.

  • Related