用2×2的字符分割字符串,最优雅的Ruby语句是什么?(复制)

时间:2022-08-22 13:12:53

This question already has an answer here:

这个问题已经有了答案:

I have the string "abigword" and I want to take the array ["ab", "ig", "wo", "rd"]. To generalize, given a string, I want to take the array of its constituent characters paired two-by-two.

我有一个字符串"abigword"我想取数组"ab" ig" wo" rd"为了推广,给定一个字符串,我想取它的组成字符的数组,成对的2乘2。

What is the most elegant Ruby way to do that?

最优雅的Ruby方法是什么?

2 个解决方案

#1


10  

"abigword".scan(/../) # => ["ab", "ig", "wo", "rd"]

It can also handle odd number of chars if you want:

它也可以处理奇数字符,如果你想:

"abigwordf".scan(/..?/) # => ["ab", "ig", "wo", "rd", "f"]

#2


3  

Two non-regexp versions:

两个non-regexp版本:

#1:
p "abigword".chars.each_slice(2).map(&:join) #=> ["ab", "ig", "wo", "rd"]

#2:
s, a = "abigword", []
a << s.slice!(0,2) until s.empty?
p a #=> ["ab", "ig", "wo", "rd"]

#1


10  

"abigword".scan(/../) # => ["ab", "ig", "wo", "rd"]

It can also handle odd number of chars if you want:

它也可以处理奇数字符,如果你想:

"abigwordf".scan(/..?/) # => ["ab", "ig", "wo", "rd", "f"]

#2


3  

Two non-regexp versions:

两个non-regexp版本:

#1:
p "abigword".chars.each_slice(2).map(&:join) #=> ["ab", "ig", "wo", "rd"]

#2:
s, a = "abigword", []
a << s.slice!(0,2) until s.empty?
p a #=> ["ab", "ig", "wo", "rd"]