Ruby Block:将proc的每一行的结果存储到变量中?

时间:2012-05-15 00:27:32

标签: ruby eval block proc

我想知道某人(比如我自己=))是否可以创建一些方法来做这样的事情:

x = magic_method do
  create_string "some_string" # a method that returns "This is <some string>\n "
  create_string "other_string"
  create_string "third_string"
end

然后返回

puts x #=> This is some_string\n This is other_string\n This is third_string

1 个答案:

答案 0 :(得分:0)

有几种选择。最简单的方法是改变原始字符串:

def create_string(str)
  str.sub!(/\A/, "This is ") << "\n"
end