代码之家  ›  专栏  ›  技术社区  ›  more or less

这种连接的操作顺序是什么?

  •  2
  • more or less  · 技术社区  · 16 年前
    x = "hello" " world".to_sym
    puts x.class
    

    Symbol
    

    但如果我稍微改变一下,使用+而不是空格分隔hello和world字符串,我会得到一个错误:

    x = "hello" + " world".to_sym
    puts x.class
    

    in `+': can't convert Symbol into String (TypeError)
    

    2 回复  |  直到 16 年前
        1
  •  4
  •   rfunduk    16 年前

    第一个例子是句法糖,通常你会看到这样写:

    x = "Here is a string that " \
        "I want to split across " \
        "several lines..."
    

    所以这首先发生在 to_sym

    x = "hello".+( "world".to_sym )
    

    String#+ 不能用符号作为参数做任何有用的事情。

    简而言之,如果你想做的话,不要做第一件事 "hello world".to_sym 无论出于什么原因,你都不能这样写,然后使用括号: ("hello" + " world").to_sym

        2
  •  1
  •   Paige Ruten    16 年前

    两个或多个字符串

    "hello" " world"
    

    string "hello world"

    "hello" + " world"
    

    string "hello" , method + ,以及 string " world"