What does ?/ mean in Ruby? [duplicate]

2020-06-12 02:45发布

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?

标签: ruby string
3条回答
家丑人穷心不美
2楼-- · 2020-06-12 03:16
$>  "/" == ?/ 
=> true

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

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-06-12 03:30

? 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"
查看更多
劫难
4楼-- · 2020-06-12 03:32

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" 
查看更多
登录 后发表回答