2

I am reading an empty HTML-File like this:

file = File.read("file_path/file.html", "wb")

Why does that throw this TypeError?

no implicit conversion of String into Integer



Log:

Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.0ms)

TypeError (no implicit conversion of String into Integer):
  app/controllers/abc_controller.rb:49:in `read'
  app/controllers/abc_controller.rb:49:in `build'
2
  • show full exception log please Commented Dec 11, 2016 at 20:14
  • @sig added log entry Commented Dec 11, 2016 at 20:22

2 Answers 2

5

If the file is empty, what do you want to read exactly?

The second parameter for File#read is optional, and should be the length of the String you want to read out of the file. "wb" isn't an Integer, hence the error messsage.

The parameters you used look more like open.

Read a file

If you want to read the file, just use

content = File.read(filename)

Write a file

If you want to write it, you can use

File.open(filename,'w+') do |file|
  file.puts "content"
end

'w+' is a file mode which :

Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

Existence of a file

If you want to check that a file exists :

File.exists?(filename)

Is a file empty?

If you want to check that an existing file is empty :

File.size(filename)==0

The file could be full of whitespaces (size > 0, but still "empty"). With Rails :

File.read(filename).blank?
Sign up to request clarification or add additional context in comments.

5 Comments

Is there a way to check if the file is empty or not?
With w+, the existing file will be overwritten. If the file doesn't exist, it is created. What do you want to do exactly?
I want to get the content of a file I created. But I don't know if that file is empty or not. If it is empty it throws an error. So I need to precheck whether that file is empty or not.
file.size.zero? perhaps.
That is what I needed. Thanks!
0

For reading a file you can use rb instead of wb.

data = File.open("ur path","rb")

2 Comments

data isn't data in this case, it's a file object. Not its content.
@EricDuminil Yaa you are right data is file object you can iterate using data do |file| file.puts "content" end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.