Question: Question:
If there is a possibility that the argument is nil
when checking the existence of the file with File.exist?
File.exist?(filename) if filename
If the filename
is nil
, it returns nil
, and if it is a String
, is there a standard way to write File.exist?
a form similar to try
?
If I need to define the method myself, I'm thinking of keeping the current writing style, but if there is a better writing style, I'd like to ask a question.
I'm thinking of adopting a form that reads all usable methods such as active_support
.
Answer: Answer:
I don't know how to write the standard,
File.exist?(filename.to_s)
If so, the existence check can be executed regardless of whether the filename
is nil
or String
.
> File.exists?(nil)
TypeError: no implicit conversion of nil into String
from (irb):1:in `exists?'
from (irb):1
from /Users/jit/.rbenv/versions/2.2.0/bin/irb:11:in `<main>'
> File.exists?(nil.to_s)
=> false
By the way, if you want to distinguish between true / false / nil and return it, it is difficult to give an appropriate answer unless you include the background. (Maybe you're trying to do something special)
Normally, both false / nil are treated as false, so I think it is a rare case to distinguish them.