在Ruby中将字符串切成给定长度的块的最佳方法是什么? [英] What is the best way to chop a string into chunks of a given length in Ruby?

查看:166
本文介绍了在Ruby中将字符串切成给定长度的块的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种优雅有效的方法,将一个字符串分块为Ruby中给定长度的子字符串。



到目前为止,我能做到的最好

  def块(字符串,大小)
(0 ..(string.length-1) /size).map{|i|string[i*size,size]}
结束

>> chunk( abcdef,3)
=> [ abc, def]
>> chunk( abcde,3)
=> [ abc, de]
>> chunk( abc,3)
=> [ abc]
>> chunk( ab,3)
=> [ ab]
>> chunk(,3)
=> []

您可能想要 chunk(,n)返回 [] 而不是 [] 。如果是这样,只需将其添加为方法的第一行即可:

 如果string.empty是否返回[]? 

您会建议任何更好的解决方案吗?



编辑



感谢Jeremy Ruten提供的这种优雅而有效的解决方案:

  def块(字符串,大小)
string.scan(/。{1,#{size}} /)
结尾

编辑



string.scan解决方案大约需要60秒才能将512k砍成1k块10000次,而原始的基于切片的解决方案只需要2.4秒。

解决方案

使用 String#scan

 > ;> ‘abcdefghijklmnopqrstuvwxyz’.scan(/。{4} /)
=> [b] b>> [[abcd], efgh, ijkl, mnop, qrst, uvwx] ‘abcdefghijklmnopqrstuvwxyz’.scan(/。{1,4} /)
=> [ abcd, efgh, ijkl, mnop, qrst, uvwx, yz]
>> ‘abcdefghijklmnopqrstuvwxyz’.scan(/。{1,3} /)
=> [b] b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b。 pre>

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:

def chunk(string, size)
  (0..(string.length-1)/size).map{|i|string[i*size,size]}
end

>> chunk("abcdef",3)
=> ["abc", "def"]
>> chunk("abcde",3)
=> ["abc", "de"]
>> chunk("abc",3)
=> ["abc"]
>> chunk("ab",3)
=> ["ab"]
>> chunk("",3)
=> []

You might want chunk("", n) to return [""] instead of []. If so, just add this as the first line of the method:

return [""] if string.empty?

Would you recommend any better solution?

Edit

Thanks to Jeremy Ruten for this elegant and efficient solution: [edit: NOT efficient!]

def chunk(string, size)
    string.scan(/.{1,#{size}}/)
end

Edit

The string.scan solution takes about 60 seconds to chop 512k into 1k chunks 10000 times, compared with the original slice-based solution which only takes 2.4 seconds.

解决方案

Use String#scan:

>> 'abcdefghijklmnopqrstuvwxyz'.scan(/.{4}/)
=> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"]
>> 'abcdefghijklmnopqrstuvwxyz'.scan(/.{1,4}/)
=> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx", "yz"]
>> 'abcdefghijklmnopqrstuvwxyz'.scan(/.{1,3}/)
=> ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"]

这篇关于在Ruby中将字符串切成给定长度的块的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆