Ruby 隐晦的 Ruby 语法:单字符的字符串

5long · 2013年05月17日 · 最后由 goinaction 回复于 2013年05月17日 · 2321 次阅读

今天看 HighLine 库的源码意外发现的, 语法是一个问号紧跟一个字符, 等价于这个只含一个该字符的字符串:

require "minitest/autorun"

describe "?y" do
  it "is the same thing as 'y'" do
    ?y.must_equal 'y'
  end
end

翻了一下镐头书第三版,里面居然有收纳这个语法。并且给出了这样的评价:

Do yourself a favor and immediately forget this section. It’s far easier to use regular octal and hex escape sequences than to remember these ones. Use "a" rather than ?a, and use "\n" rather than ?\n.

出于装X的考虑,以后要找机会多用www

共收到 3 条回复

字符串字面量各种神奇...

puts <<-A, <<-B
  hello
A
  world
B
"\C-x" # ctrl + x

这个用法是1.9新加的,和1.8.7还不兼容。

[~/work] $ ruby -v -e "p ?a"
ruby 1.8.7 (2012-02-08 patchlevel 358) [universal-darwin12.0]
97

[~/work] $ ruby -v -e "p ?a"
ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-darwin12.3.0]
"a"
# A shortcut to HighLine.ask() a question that only accepts "yes" or "no"
# answers ("y" and "n" are allowed) and returns +true+ or +false+
# (+true+ for "yes").  If provided a +true+ value, _character_ will cause
# HighLine to fetch a single character response. A block can be provided
# to further configure the question as in HighLine.ask()
# 
# Raises EOFError if input is exhausted.
#
def agree( yes_or_no_question, character = nil )
  ask(yes_or_no_question, lambda { |yn| yn.downcase[0] == ?y}) do |q|
    q.validate                 = /\Ay(?:es)?|no?\Z/i
    q.responses[:not_valid]    = 'Please enter "yes" or "no".'
    q.responses[:ask_on_error] = :question
    q.character                = character

    yield q if block_given?
  end
end

哇,他这种写法是可以兼容1.9和1.8的.... 1.8的String#[] 返回ascii,?也返回ascii 1.9的String#[] 返回字符串,?也返回字符串

#1楼 @luikore 《Ruby编程语言》里面给的例子好像就这样

5long ruby 中 == ?. 的用法解释 中提及了此贴 09月07日 21:19
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册