Steven Rumbalski
Steven Rumbalski

Reputation: 45552

Chunk a string into unequal lengths

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

Answers (3)

dbenhur
dbenhur

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

David Grayson
David Grayson

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

Victor Moroz
Victor Moroz

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

Related Questions