是否可以编写一个带有字符串块的函数,对字符串执行某些操作,然后返回带有字符串的数组?
def collect_string(&block)
# just toss them into an array and return it
return ...
end
a = collect_string {
"string 1"
"string 2"
"string 3"
}
当我打印出a
时,我应该
["string 1", "string2", "string3"]
现在假设我决定改变主意,并希望先用字符串做更多事情。也许我想首先删除所有的元音,或者只是抓住前3个字符。
答案 0 :(得分:0)
这真是不这些块的用途。无论如何你要创建一个字符串数组,那么为什么不使用数组开始呢?
def collect_string &block
v = block.call
# do something with v
end
# block returning array
a = collect_string {[
"string 1",
"string 2",
"string 3"
]}
如果您在示例中使用了一个块,那么它将仅返回“string 3”,即最后一个表达式。以前的字符串丢失了。