Reputation: 45552
I want to divide a string into chunks of unequal size (as given by lens
). My code works, but does not feel like idiomatic Ruby. Any suggestions?
s = "red 4827spoon jimmy john "
lens = [6, 4, 12, 13]
i = 0
row = lens.collect {|len|
i += len
s[i-len, len].strip
}
Gives
["red", "4827", "spoon", "jimmy john"]
Upvotes: 1
Views: 138
Reputation: 20398
I rather like Victor's unpack solutions, though they may be a bit obscure for many rubiests. inject
may be a bit more prosaic:
lens.inject([0]) {|spans,len|
start = spans.pop
spans << s[start,len].strip << start+len
}[0...-1]
Upvotes: 1
Reputation: 87486
This is probably less efficient because it modifies the original string a lot, but how about:
row = lengths.collect { |n| s.slice!(0..(n-1)).strip }
Upvotes: 2
Reputation: 9225
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"]
Upvotes: 1