tags:

views:

359

answers:

2

The documentation say:

File.size(file_name) => integer
Returns the size of file_name.

File.size?(file_name) => Integer or nil Returns nil if file_name doesn‘t exist or has zero size, the size of the file otherwise.

On practice (ruby 1.8.7 i386-mswin32):

File.size?('c:/dir')   
# => nill
File.size('c:/dir')
# => 0

The nil makes sence for me, but 0? I would expect an exception instead. Do anybody see reason for this?

+1  A: 

Directories are files. Well, I suppose in some operating systems they aren't, but in all Unix-based ones they are.

Of course, in Unix systems, directories in "regular" file systems (i.e., ones that have real files, not /proc or the like) have non-zero size too.

File.size('/etc')
=> 12288
Chris Jester-Young
Yeah, but the "c:/dir" should have been a clue that he's not on Unix.
JSBangs
Ah.. I see now, thanks.
alex2k8
@JS Bangs: That's true, however, I thought that Ruby, being designed for Unix originally, has features coded in to ensure some Unix compatibility, such as not throwing an exception when File.size is called on a directory. :-P
Chris Jester-Young
@JS Bangs. Actually ruby interpreter knows the OS it is running on, but I think the developers saw no sence in doing things differently on different OS's.
alex2k8
It would be pretty schizophrenic to return the directory size on Unix and throw an exception on Windows. Finding out if the thing doesn't really have a size is the whole point of the `size?` variant.
Chuck
+1  A: 

Exceptions are as a general rule slow, so whenever the issue is not critical, it's better to use return flags for efficiency reasons. As long as the file/directory exists, I see no use for an exception, and in fact would find one annoying. Like this, calculating total file size is simply adding them up with no error-handling required.

krdluzni