11

I just stumbled across this piece of code:

if source[0] != ?/
  source = compute_asset_path(source, options)
end

What's this "?/"? I've never seen writing strings this way.

$ irb
2.0.0p247 :001 > ?/
=> "/" 

Apparently it works for single characters only:

2.0.0p247 :001 > ?a
 => "a" 
2.0.0p247 :002 > ?foo
SyntaxError: (irb):2: syntax error, unexpected '?'

What does ? mean?

aschepler
  • 70,891
  • 9
  • 107
  • 161
Simone
  • 20,302
  • 14
  • 79
  • 103

3 Answers3

12

? is used to represent single character string literals. Like ?a,?b but not ?ab.

To answer the comment of OP :

Yes, they are.

irb(main):001:0> ?x + 'y'
=> "xy"
irb(main):002:0> 'x' + 'y'
=> "xy"
Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • Whether it is single quote or double quote, it does not make difference. In order to interpolate, you need `#{}`, which cannot be written in a single character anyway. – sawa Mar 06 '14 at 13:10
  • @sawa You are correct. – Arup Rakshit Mar 06 '14 at 13:11
  • 1
    But what's the actual difference between `?a` and `"a"`? Are they interchangeable? – Simone Mar 06 '14 at 13:14
  • `?a` is left probably only for compatibility with legacy code. Other than that, there is no practical value. – sawa Mar 06 '14 at 13:16
  • 2
    @simone it is very useful in `code-golf`(http://codegolf.stackexchange.com/questions/9004/play-a-sound-any-sound/10555#10555) and internal ruby jokes, like `almost_sinatra` (https://github.com/rkh/almost-sinatra/blob/master/almost_sinatra.rb) – Uri Agassi Mar 06 '14 at 13:54
4

In Ruby 1.8.x series, it return ASCII value

alok@alok-desktop:~$ rvm use ruby-1.8.7-p370
Using /home/alok/.rvm/gems/ruby-1.8.7-p370
alok@alok-desktop:~$ irb
1.8.7-p370 :001 > ?F
 => 70 

In Ruby 1.9+ it returns same character string

1.9.2-p320 :018 > ?A
 => "A" 
Alok Anand
  • 3,346
  • 1
  • 20
  • 17
2
$>  "/" == ?/ 
=> true

another version of string but shorter :) also true: %{/}

itsnikolay
  • 17,415
  • 4
  • 65
  • 64