【问题标题】:Where is Ruby's string literal juxtaposition feature officially documented?Ruby 的字符串文字并置功能在哪里正式记录?
【发布时间】:2013-08-12 18:12:31
【问题描述】:

我最近意识到,如果您将一系列 Ruby 字符串文字(例如 'a' "b" 'c')并置,它就相当于将这些字符串文字串联起来。但是,我在任何地方都找不到此语言功能的文档。我使用术语“并置”和“连接”进行了搜索,但只在几个 StackOverflow 响应中找到了对它的引用。谁能给我一个明确的参考?

【问题讨论】:

标签: ruby


【解决方案1】:

更新

这是 Ruby 附带的 RDoc 中的 now officially documented

下次构建文档时,更改将传播到RubyDoc

添加的文档:

Adjacent string literals are automatically concatenated by the interpreter:

  "con" "cat" "en" "at" "ion" #=> "concatenation"
  "This string contains "\
  "no newlines."              #=> "This string contains no newlines."

Any combination of adjacent single-quote, double-quote, percent strings will
be concatenated as long as a percent-string is not last.

  %q{a} 'b' "c" #=> "abc"
  "a" 'b' %q{c} #=> NameError: uninitialized constant q

原创

目前,官方 ruby​​ 文档中没有任何内容,但我认为应该如此。正如评论中所指出的,文档的逻辑位置是:http://www.ruby-doc.org/core-2.0/doc/syntax/literals_rdoc.html#label-Strings

我在ruby/ruby 上打开了pull request,并添加了文档。

如果此拉取请求被合并,它将自动更新http://www.ruby-doc.org。如果/何时发生这种情况,我会更新这篇文章。 ^_^

我在网上找到的唯一其他提及的是:

【讨论】:

  • 谢谢,克里斯。不过,我认为问题 cmets 中提到的ruby-doc.org/docs/ProgrammingRuby/html/language.html 与您提到的属于同一类别,不是吗?
  • @PeterAlfvin 该文档与字符串文字直接相关,因此我认为它属于该语言附带的文字文档。 Programming Ruby 这本书很棒,但很老。它记录了 ruby​​ 1.6。我认为这是 ruby​​ 的一个简洁功能,应该是随附文档的一部分。
  • 我完全同意你的看法(这就是我接受你的回答的原因:-))并且只是建议你可能想在你的答案的“其他提及”部分中包含 Programming Ruby 书,特别是因为它比 Ruby 编程语言 (imho) 更有效地记录它。
  • 请在更新时也给我一个通知..请.. :)
  • @PeterAlfvin 明白了! ^_^ 我误会了。我的错。
【解决方案2】:

The Ruby Programming Language, page 47中有引用。

看起来它是故意在解析器中的,用于您想要在代码中拆分字符串文字但又不想为连接它们(并创建 3 个或更多字符串)付出代价的情况。没有换行符的长字符串,并且不需要行长的破坏代码,就是一个很好的例子

text = "This is a long example message without line breaks. " \
    "If it were not for this handy syntax, " \
    "I would need to concatenate many strings, " \
    "or find some other work-around"

【讨论】:

    【解决方案3】:

    除了pickaxe reference,还有一些unit tests

    # compile time string concatenation
    assert_equal("abcd", "ab" "cd")
    assert_equal("22aacd44", "#{22}aa" "cd#{44}")
    assert_equal("22aacd445566", "#{22}aa" "cd#{44}" "55" "#{66}")
    

    【讨论】:

      【解决方案4】:

      如果你想在多行中打破一个长的单引号字符串文字而不在其中嵌入新行。

      只需将其分解为多个相邻的字符串文字,ruby 解释器将在解析过程中将它们连接起来。

      str = "hello" "all"
      
      puts str #=> helloall
      

      但请记住,您必须转义文字之间的换行符,以便 ruby​​ 不会将换行符解释为语句终止符。

      str = "hello" \
            " all" \
            " how are you."
      
      puts str #=> hello all how are you
      

      【讨论】:

      • 问题是问这是在哪里记录的,而不是为什么会发生这种情况。
      猜你喜欢
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      相关资源
      最近更新 更多