我想将一个字符串分成不等大小的块(由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"]
答案 0 :(得分:2)
这可能效率较低,因为它会大量修改原始字符串,但是如何:
row = lengths.collect { |n| s.slice!(0..(n-1)).strip }
答案 1 :(得分:1)
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"]
答案 2 :(得分:1)
我更喜欢Victor的解包方案,尽管对于许多红宝石来说它们可能有点模糊。 inject
可能会更平淡无奇:
lens.inject([0]) {|spans,len|
start = spans.pop
spans << s[start,len].strip << start+len
}[0...-1]