我想将一个字符串分成大小不等的块(由 给出lens
)。我的代码有效,但感觉不像是惯用的 Ruby。有什么建议么?
s = "red 4827spoon jimmy john "
lens = [6, 4, 12, 13]
i = 0
row = lens.collect {|len|
i += len
s[i-len, len].strip
}
给
["red", "4827", "spoon", "jimmy john"]
我想将一个字符串分成大小不等的块(由 给出lens
)。我的代码有效,但感觉不像是惯用的 Ruby。有什么建议么?
s = "red 4827spoon jimmy john "
lens = [6, 4, 12, 13]
i = 0
row = lens.collect {|len|
i += len
s[i-len, len].strip
}
给
["red", "4827", "spoon", "jimmy john"]
这可能效率较低,因为它会大量修改原始字符串,但是如何:
row = lengths.collect { |n| s.slice!(0..(n-1)).strip }
s = "red 4827spoon jimmy john "
lens = [6, 4, 12, 13]
p s.unpack(lens.map{ |i| "A#{i}" }.join) #=>["red", "4827", "spoon", "jimmy john"]
p s.unpack(lens.map(&"A%d".method(:%)).join) #=> ["red", "4827", "spoon", "jimmy john"]
我更喜欢 Victor 的解包解决方案,尽管对于许多 rubies 来说它们可能有点晦涩难懂。 inject
可能有点平淡:
lens.inject([0]) {|spans,len|
start = spans.pop
spans << s[start,len].strip << start+len
}[0...-1]