我正在尝试制作一个代码,该代码返回字符串中的所有偶数值。我创建的代码似乎是这样做的,但是它不会返回白色空间,因此最终测试失败了。有人可以帮助我理解为什么它返回所有信件,但没有任何字母?
# Every Other Letter Define a method, #every_other_letter(string),
# that accepts a string as an argument. This method should return a
# new string that contains every other letter of the original string,
# starting with the first character. Treat white-space and punctuation
# the same as letters.
def every_other_letter(string)
idx = 0
final = []
while idx < string.length
letters = string[idx].split
final = final + letters
idx = idx + 2
end
p final = final.join
end
puts "------Every Other Letter------"
puts every_other_letter("abcde") == "ace"
puts every_other_letter("i heart ruby") == "ihatrb"
puts every_other_letter("an apple a day...") == "a pl a.."
这返回:
------Every Other Letter------
"ace"
true
"ihatrb"
true
"apla.."
false
=> nil
只是获取所有偶数字符的另一种方法,使用正则表达式抓住对并通过其第一个字符替换每个对:
"abcd fghi".gsub(/(.)./, '1')
=> "ac gi"
或找到它们并加入:
"abcd fghi".scan(/(.).?/).join
=> "ac gi"
问题是,正如指向@sergio所述,您正在使用单个字符上的拆分,因此,您在数组中"转换"了该字母。您可以做的就是将string[idx]
推向最终,它对您有效。
其他方式,您可以将字符串分开,使用SELECT获得索引处的字符,然后加入它们:
p "an apple a day...".chars.select.with_index { |_, i| i.even? }.join == "a pl a.." # true