2

我有字符串"abigword",我想拿数组["ab", "ig", "wo", "rd"]。概括地说,给定一个字符串,我想将其组成字符的数组两两配对。

最优雅的 Ruby 方法是什么?

4

2 回答 2

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

如果需要,它还可以处理奇数个字符:

"abigwordf".scan(/..?/) # => ["ab", "ig", "wo", "rd", "f"]
于 2013-10-30T11:47:42.250 回答
3

两个非正则表达式版本:

#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"]
于 2013-10-30T12:59:09.737 回答