heredoc 中的 Ruby 语法?

标签 ruby

我想在 Ruby heredoc 中迭代一个数组。

<<-BLOCK
Feature: User logs in
  In order to post content
  As an user
  I want to log in

<< Here i want to iterate scenarios >>
BLOCK

“场景”是我要循环的数组。对于我要打印的每个元素:

Scenario: #{scenario}
  Given
  When
  Then

例如,如果“场景”包含:

scenarios[0] = "User successfully logs in"
scenarios[1] = "User failed to log in"

我希望 heredoc 字符串为:

<<-BLOCK
Feature: #{feature}
  In order to #{in_order_to}
  As #{as}
  I want #{i_want}

Scenario: User successfully logs in
  Given
  When
  And

Scenarios: User failed to log in
  Given
  When
  And
BLOCK

我如何在 Ruby heredoc 中进行迭代?

最佳答案

您可以使用 ERB。它会更干净,而不是更多的代码:

require 'erb'
s = ERB.new(<<-BLOCK).result(binding)
Feature: User logs in
  In order to post content
  As an user
  I want to log in

<% scenarios.map do |x| %>
  Scenario: <%= x %>
  Given
  When
  Then
<% end %>
BLOCK

第一行可能看起来很奇怪,所以我将其分解

s = ERB.new(<<-BLOCK).result(binding)

ERB.new使用传递的字符串作为其内容创建一个新的 erb 模板。 <<-BLOCK是一个 heredoc,表示将后面的 heredoc 值放入表达式中。 result(binding)在当前上下文中评估模板(binding 是当前评估的上下文)。

随着模板变大,您可以从那里轻松地将模板提取到文件中。

More about Ruby's heredocs by James Edward Gray II

关于heredoc 中的 Ruby 语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3688064/

相关文章:

javascript - 如何将数组的Javascript字符串转换为数组?

ruby - 减少数字数组(序列)

ruby-on-rails - 克隆记录并将远程文件复制到新位置?

ruby - 命令行获取gem路径

ruby - 是否可以在 ruby​​ 中为 to_yaml 指定格式选项?

html - 为什么 Nokogiri 会删除内容?

ruby - 在 Ruby 中 append 到 JSON 数组

ruby - 为什么这个简单的 Ruby 代码不能在 HAML 中运行?

ruby-on-rails - week_field 在序列化和反序列化后给出错误的周

ruby-on-rails - 在 rails 3 中处理 HEAD 和 GET 请求时出现问题