如何在ruby中分割x相等的字符串?

时间:2022-01-22 21:39:27

I have a string in ruby like this:

我有一个像这样的ruby字符串:

str = "AABBCCDDEEFFGGHHIIJJ01020304050607080910"
# 20 letters and 20 numbers in this case

I want to split this in half, which I can do like this:

我想把它分成两半,我可以这样做:

str[0, str.length/2]

or

str.split(0, str.length/2)

After that, I need to make arrays with the chars but with length 2 for each element like this:

之后,我需要用chars创建数组,但是每个元素的长度都是2:

["AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ"],
[01, 02, 03, 04, 05, 06, 07, 08, 09, 10]

The problem is, I can't find a concise way to convert this string. I can do something like this

问题是,我找不到一个简洁的方法来转换这个字符串。我可以这样做

arr = []
while str.length > 0 do
  arr << str[0, 1]
  str[0, 1] = ""
end

but I rather want something like str.split(2), and the length of the string may change anytime.

但是我想要的是字符串。split(2),字符串的长度可以随时改变。

3 个解决方案

#1


24  

How about this?

这个怎么样?

str.chars.each_slice(2).map(&:join)

#2


15  

You could use the scan method:

你可以使用扫描方法:

1.9.3p194 :004 > a = 'AABBCCDDEEC'
 => "AABBCCDDEEC" 
1.9.3p194 :005 > a.scan(/.{1,2}/)
 => ["AA", "BB", "CC", "DD", "EE", "C"] 

#3


-1  

2.1.0 :642 > "d852".scan(/../) => ["d8", "52"]

2.1.0:642 >“d852”.scan(/. /) => ["d8", "52"]

#1


24  

How about this?

这个怎么样?

str.chars.each_slice(2).map(&:join)

#2


15  

You could use the scan method:

你可以使用扫描方法:

1.9.3p194 :004 > a = 'AABBCCDDEEC'
 => "AABBCCDDEEC" 
1.9.3p194 :005 > a.scan(/.{1,2}/)
 => ["AA", "BB", "CC", "DD", "EE", "C"] 

#3


-1  

2.1.0 :642 > "d852".scan(/../) => ["d8", "52"]

2.1.0:642 >“d852”.scan(/. /) => ["d8", "52"]