ruby - 双小于负 "<<-"符号在 ruby 中有什么意义吗?

标签 ruby syntax

我正在努力让自己熟悉 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/

相关文章:

rust - `&[][..]` 在 Rust 中意味着什么?

Java:为什么 "throw new Exception()"必须是 "add Exception to method signature",但 "throw new RuntimeException()"不是

ruby - 在 Ruby on Rails 应用程序中实现匹配算法

ruby - 如何重命名目录?

arrays - Ruby,Array.select 与元素的数量

syntax - Roslyn 语法树差异

ruby-on-rails - 解释 Ruby on Rails 中的迭代器语法

ruby-on-rails - Gmaps4Rails.clear_marker 类型错误 : Cannot read property 'serviceObject' of null

ruby - Ruby 中的方法访问

PHPdesigner 8 语法高亮