Ruby-on-rails Rails 3 中的字符串连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15864068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:46:40  来源:igfitidea点击:

String concatenation in Rails 3

ruby-on-railsrubystringconcatenation

提问by valk

I'm wondering why this is so: Ruby concatenates two strings if there is a space between the plus and the next string. But if there is no space, does it apply some unary operator?

我想知道为什么会这样:如果加号和下一个字符串之间有空格,Ruby 会连接两个字符串。但是如果没有空格,它是否应用了一些一元运算符?

params['controller'].to_s + '/'
# => "posts/"

params['controller'].to_s +'/'
# => NoMethodError: undefined method `+@' for "/":String

回答by Matt Glover

The parser is interpreting +'/'as the first parameter to the to_smethod call. It is treating these two statements as equivalent:

解析器将解释+'/'to_s方法调用的第一个参数。它将这两个语句视为等价的:

> params['controller'].to_s +'/'
# NoMethodError: undefined method `+@' for "/":String

> params['controller'].to_s(+'/')
# NoMethodError: undefined method `+@' for "/":String

If you explicitly include the parenthesis at the end of the to_smethod call the problem goes away:

如果您在to_s方法调用的末尾明确包含括号,问题就会消失:

> params['controller'].to_s() +'/'
=> "posts/"

回答by OneChillDude

If you want to concatenate a string, the safest way is to write "#{params[:controller].to_s} /"ruby's string escaping is safer and better in many cases

如果要拼接一个字符串,最安全的方式是写"#{params[:controller].to_s} /"ruby的字符串转义在很多情况下更安全更好

回答by Arup Rakshit

Look closely the error:

仔细看错误:

p "hi".to_s +'/'
p "hi".to_s -'2'

#=> in `<main>': undefined method `+@' for "/":String (NoMethodError)

This is because unary operator+,-etc is defined only Numericclass objects. It will be clear if you look at the code below:

这是因为unary operator+, -etc 只定义了Numeric类对象。如果你看看下面的代码就会很清楚:

p "hi".to_s +2
#=>in `to_s': wrong number of arguments (1 for 0) (ArgumentError)

Now the above error is exactly right for to_s. As to_sdoesn't take any argument when it is called.

现在上述错误完全适用于to_s. Asto_s被调用时不接受任何参数。

Correct version is:

正确的版本是:

p "hi".to_s + '2' #=> "hi2"