I am learning Ruby and found this code sample in some documentation:
require 'find'
total_size = 0
Find.find(ENV["HOME"]) do |path|
if FileTest.directory?(path)
if File.basename(path)[0] == ?.
Find.prune # Don't look any further into this directory.
else
next
end
else
total_size += FileTest.size(path)
end
end
The purpose is to sum up the file sizes of all files in a tree, excluding directories that start with a dot. The line if File.basename(path)[0] == ?.
is obviously performing the directory name test. I would have written it like this:
if File.basename(path)[0] == "."
What does ?.
do? (Could be a typo, I suppose.) I have not seen this syntax described elsewhere.
?.
returns the ASCII value of the dot. You can put pretty much any char after the question mark to get its ASCII value, like ?a
or ?3
or ?\\
, etc. The reason they are not comparing it to the string "."
is that when you index into a string, you get the ASCII value of the char at that index rather than the char itself. To get the char at a certain index you can use [0, 1]
as the index. So the options are:
if File.basename(path)[0] == ?.
Or:
if File.basename(path)[0, 1] == "."
Or even:
if File.basename(path)[0].chr == "."
It is a shorthand for the ASCII code point of the "." character. See the documentation on numeric literals in the Ruby syntax.
>> ?.
=> 46
>> ?a
=> 97
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With