我试图创建一个返回字符串中所有偶数值的代码。我创建的代码似乎是这样做的,但它不会返回空格,因此最终的测试失败了。有人可以帮我理解为什么它会返回所有的字母,但没有一个空格?
# 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
答案 0 :(得分:4)
另一种获取所有偶数索引字符的方法,使用正则表达式来抓取对并用每个第一个字符替换每对:
"abcd fghi".gsub(/(.)./, '\1')
=> "ac gi"
或找到他们并加入他们:
"abcd fghi".scan(/(.).?/).join
=> "ac gi"
答案 1 :(得分:2)
问题是,正如@Sergio指出的那样,你在单个字符串上使用拆分,所以,你要转换&#34;转换&#34;数组中的那个字母。你可以做的就是将string[idx]
推到最后,这样就适合你。
换句话说,你可以拆分字符串,使用select获取索引为偶数的字符,然后加入它们:
p "an apple a day...".chars.select.with_index { |_, i| i.even? }.join == "a pl a.." # true