What is the best way to chop a string into chunks of a given length in Ruby?

前端 未结 9 2075
陌清茗
陌清茗 2020-12-12 18:40

I have been looking for an elegant and efficient way to chunk a string into substrings of a given length in Ruby.

So far, the best I could come up with is this:

9条回答
  •  北海茫月
    2020-12-12 19:16

    A better solution which takes into account the last part of the string which could be less than the chunk size:

    def chunk(inStr, sz)  
      return [inStr] if inStr.length < sz  
      m = inStr.length % sz # this is the last part of the string
      partial = (inStr.length / sz).times.collect { |i| inStr[i * sz, sz] }
      partial << inStr[-m..-1] if (m % sz != 0) # add the last part 
      partial
    end
    

提交回复
热议问题