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

前端 未结 9 2074
陌清茗
陌清茗 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:23
    test.split(/(...)/).reject {|v| v.empty?}
    

    The reject is necessary because it otherwise includes the blank space between sets. My regex-fu isn't quite up to seeing how to fix that right off the top of my head.

    0 讨论(0)
  • 2020-12-12 19:27

    Here is another way to do it:

    "abcdefghijklmnopqrstuvwxyz".chars.to_a.each_slice(3).to_a.map {|s| s.to_s }
    

    => ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"]

    0 讨论(0)
  • 2020-12-12 19:32

    I think this is the most efficient solution if you know your string is a multiple of chunk size

    def chunk(string, size)
        (string.length / size).times.collect { |i| string[i * size, size] }
    end
    

    and for parts

    def parts(string, count)
        size = string.length / count
        count.times.collect { |i| string[i * size, size] }
    end
    
    0 讨论(0)
提交回复
热议问题