什么?/在Ruby中意味着什么?

Sim*_*one 11 ruby string

我偶然发现了这段代码:

if source[0] != ?/
  source = compute_asset_path(source, options)
end
Run Code Online (Sandbox Code Playgroud)

这是什么" ?/"?我从未见过以这种方式写字符串.

$ irb
2.0.0p247 :001 > ?/
=> "/" 
Run Code Online (Sandbox Code Playgroud)

显然它只适用于单个字符:

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

什么?意思?

Aru*_*hit 12

?用于表示单个字符串文字.喜欢?a,?b但不是?ab.

回答OP 的评论:

对,他们是.

irb(main):001:0> ?x + 'y'
=> "xy"
irb(main):002:0> 'x' + 'y'
=> "xy"
Run Code Online (Sandbox Code Playgroud)

  • @simone在`code-golf`(http://codegolf.stackexchange.com/questions/9004/play-a-sound-any-sound/10555#10555)和内部红宝石笑话中非常有用,比如`almost_sinatra` (https://github.com/rkh/almost-sinatra/blob/master/almost_sinatra.rb) (2认同)