Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the syntax ?. mean in this Ruby example? [duplicate]

Tags:

ruby

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.

like image 995
Paul Chernoch Avatar asked Oct 23 '09 18:10

Paul Chernoch


2 Answers

?. 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 == "."
like image 132
Paige Ruten Avatar answered Sep 28 '22 17:09

Paige Ruten


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
like image 24
Brian Campbell Avatar answered Sep 28 '22 18:09

Brian Campbell