我正在努力让自己熟悉 ruby 语法和编码风格(我是新手)。我遇到了使用 <<-
的代码,这在 Ruby 中意味着什么?代码是
def expectation_message(expectation)
<<-FE
#{expectation.message}
#{expectation.stack}
FE
end
这只是整个代码的一部分。任何帮助将不胜感激。
最佳答案
在 Ruby 中有多种定义多行字符串的方法。这是其中之一。
> name = 'John'
> city = 'Ny'
> multiline_string = <<-EOS
> This is the first line
> My name is #{name}.
> My city is #{city} city.
> EOS
=> "This is the first line\nMy name is John.\nMy city is Ny city.\n"
>
上面例子中的EOS
只是一个约定,你可以使用任何你喜欢的字符串,并且不区分大小写。通常 EOS
表示 End Of String
此外,甚至不需要 -
(破折号)。但是,允许您缩进“此处文档结束”定界符。请参阅以下示例以理解句子。
2.2.1 :014 > <<EOF
2.2.1 :015"> My first line without dash
2.2.1 :016"> EOF
2.2.1 :017"> EOF
=> "My first line without dash\n EOF\n"
2.2.1 :018 > <<-EOF
2.2.1 :019"> My first line with dash. This even supports spaces before the ending delimiter.
2.2.1 :020"> EOF
=> "My first line with dash. This even supports spaces before the ending delimiter.\n"
2.2.1 :021 >
更多信息见 https://cbabhusal.wordpress.com/2015/10/06/ruby-multiline-string-definition/
关于ruby - 双小于负 "<<-"符号在 ruby 中有什么意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33344187/