【问题标题】:ruby here-doc with a loop带有循环的 ruby​​ here-doc
【发布时间】:2011-05-16 17:01:22
【问题描述】:

你能做一个循环和here-doc吗,像这样:

array.each do |ele|
  a=<<-TEXT
   ele
   some stuff
  TEXT
end

谢谢

【问题讨论】:

  • 我不明白你在问什么。你能改写吗?你想要达到的输出结果是什么?
  • @elusive ok 更新了,除了我需要从数组中获取元素之外没有特定的输出
  • 请添加一些示例输入和输出。我不明白循环和 HERE-doc 可能是如何相关的。

标签: ruby loops heredoc


【解决方案1】:
array = %w[one two many]

array.each do |ele|
  a=<<-TEXT
  This is some text and
  this --> #{ele} <-- is the ele!

  TEXT

  puts a
end

结果

This is some text and
this --> one <-- is the ele!

This is some text and
this --> two <-- is the ele!

This is some text and
this --> many <-- is the ele!

【讨论】:

  • 啊,好吧,我把“a”放在循环的外面。不过,这是有道理的。谢谢!
  • @steenslag 是的。 Matt 想在他的问题中为a 分配一个字符串;我随机添加了puts 以了解正在发生的事情:)
  • 如果您没有在循环内分配a 并将each 设置为map,您仍然可以将puts 放在循环之外。我什至更喜欢这种方式。
  • 是的,但我需要一个变量,以便稍后在代码中使用。它没有被打印出来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
相关资源
最近更新 更多