x = "hello" " world".to_sym
puts x.class
这有效并允许我将两个字符串连接成一个符号,产生输出:
Symbol
但是如果我稍微更改它以使用 + 而不是分隔 hello 和 world 字符串的空格,我会收到一个错误:
x = "hello" + " world".to_sym
puts x.class
这会产生以下错误 -我认为这是因为它试图将“world”.to_sym 回调“转换”回字符串,然后将其连接到“hello”字符串:
in `+': can't convert Symbol into String (TypeError)
我想知道是什么使第一个示例起作用? 有谁知道这里的操作顺序是什么? 我怀疑这两个字符串实际上被视为一个字符串,它们之间的空格被忽略,并且在调用 to_sym 方法之前将它们连接起来。 实际上,我期望它的工作方式与第二个示例没有什么不同,因为我认为在尝试连接“hello”和“world”的内容之前,将在“world”字符串上调用 to_sym 。
x = "hello" " world".to_sym
puts x.class
This works and allows me to concatenate the two strings into a symbol, producing the output:
Symbol
But if I change it slightly to use a + instead of a space separating the hello and world strings, I get an error:
x = "hello" + " world".to_sym
puts x.class
This produces the following error - I think this is because it's trying to 'cast' the "world".to_sym call back to a string before concatenating it onto the "hello" string:
in `+': can't convert Symbol into String (TypeError)
I'm wondering what makes the first example work? Does anyone know what the order of operations is here? I suspect the two strings are actually treated as one, that the space between them is ignored and they are concatenated before the to_sym method is called. I actually would have expected it to work no differently than the second example because I thought the to_sym would be called on the "world" string BEFORE any attempt is made to join the contents of "hello" and "world".
发布评论
评论(2)
第一个例子是语法糖,通常你会看到这样写:
所以这首先发生,在
to_sym
之前。 在第二个示例中,您实际上是在调用:这显然是行不通的,因为
String#+
无法使用符号作为参数执行任何有用的操作。简而言之,不要执行第一个,如果您想做
"hello world".to_sym
并且无论出于何种原因都不能这样写,那么只需使用括号:(“你好”+“世界”).to_sym
The first example is syntactic sugar, normally you see this written like:
So this happens first, before
to_sym
. In the second example you are literally calling:Which is obviously not going to work since
String#+
can't do anything useful with a symbol as an argument.In short, don't do the first one, if you want to do
"hello world".to_sym
and you can't just write it like that for whatever reason then just use parenthesis:("hello" + " world").to_sym
两个或多个字符串文字并排放置,会立即被视为单个字符串文字。 当 Ruby 解释器将代码转换为标记时,它会转换
为单个标记
string "hello world"
并转换为三个标记:
string "hello"
、方法+
和字符串“world”
。 然后,当实际执行代码时,它会将字符串连接在一起。Two or more string literals put right beside each other like that are immediately treated as a single string literal. When the Ruby interpreter converts your code to tokens, it converts
to the single token
string "hello world"
and it convertsto three tokens:
string "hello"
,method +
, andstring " world"
. It would then concatenate the strings together later on when actually executing the code.