heredoc里面的Ruby语法?

前端之家收集整理的这篇文章主要介绍了heredoc里面的Ruby语法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在 Ruby heredoc中迭代一个数组.
  1. <<-BLOCK
  2. Feature: User logs in
  3. In order to post content
  4. As an user
  5. I want to log in
  6.  
  7. << Here i want to iterate scenarios >>
  8. BLOCK

“scenario”是我想要循环的数组.对于我要打印的每个元素:

  1. Scenario: #{scenario}
  2. Given
  3. When
  4. Then

例如,如果“scenario”包含:

  1. scenarios[0] = "User successfully logs in"
  2. scenarios[1] = "User Failed to log in"

我希望heredoc字符串是:

  1. <<-BLOCK
  2. Feature: #{feature}
  3. In order to #{in_order_to}
  4. As #{as}
  5. I want #{i_want}
  6.  
  7. Scenario: User successfully logs in
  8. Given
  9. When
  10. And
  11.  
  12. Scenarios: User Failed to log in
  13. Given
  14. When
  15. And
  16. BLOCK

如何在Ruby heredoc中进行迭代?

解决方法

你可以这样做,但我不确定它是最可读的方法
  1. s = <<-BLOCK
  2. Feature: User logs in
  3. In order to post content
  4. As an user
  5. I want to log in
  6.  
  7. #{scenarios.map{|x|
  8. <<-INNERBLOCK
  9. Scenario: #{x}
  10. Given
  11. When
  12. Then
  13. INNERBLOCK
  14. }}
  15.  
  16. BLOCK

猜你在找的Ruby相关文章