Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby-在返回字符串中的所有偶数值时,如何保留空格?_Ruby_While Loop_Whitespace - Fatal编程技术网

Ruby-在返回字符串中的所有偶数值时,如何保留空格?

Ruby-在返回字符串中的所有偶数值时,如何保留空格?,ruby,while-loop,whitespace,Ruby,While Loop,Whitespace,我正在尝试生成一个返回字符串中所有偶数值的代码。我创建的代码似乎可以做到这一点,但它不会返回空格,因此最终测试失败。有人能帮我理解为什么它返回所有的字母,但没有一个空格吗 # 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 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.."

正如@Sergio所指出的,问题在于,您在单个字符上使用split,因此,您在数组中“转换”该字母。您所能做的就是将
字符串[idx]
推到final,这样对您很有用

另一种方法是使用select拆分字符串,在索引为偶数的位置获取字符,然后将它们合并:

p "an apple a day...".chars.select.with_index { |_, i| i.even?  }.join == "a pl  a.." # true
"abcd fghi".scan(/(.).?/).join
=> "ac gi"

这是获取所有偶数索引字符的另一种方法,使用正则表达式获取对,并用其第一个字符替换每对:

"abcd fghi".gsub(/(.)./, '\1')
=> "ac gi"
或者找到他们并加入他们:

p "an apple a day...".chars.select.with_index { |_, i| i.even?  }.join == "a pl  a.." # true
"abcd fghi".scan(/(.).?/).join
=> "ac gi"

为什么拆分
字符串[idx]
?这将得到一个字符字符串,没有任何可拆分的内容。是的,这就是错误。字符串中没有“偶数”值。我相信你的意思是“返回索引为偶数的字符串中的所有字符”?现在,你说的“返回”是什么意思?如果
str='abcde',您是否需要返回字符串
'ace'
,数组
['a','c','e']`或其他内容。准确点!谢谢塞吉奥。我使用split是因为我对ruby不熟悉,尝试了一些不同的东西,当我尝试split时,代码工作正常,除了包含空格。感谢你的评论,我知道如果我只是将split改为split(“”),它将通过所有3项测试。当然,这仍然是不必要的,我应该清理我的代码,我将这样做。对于没有拆分的引用,发布的确切代码会产生以下错误消息:没有将字符串隐式转换为数组(repl):13:in
every_other_letter'(repl):21:in
”@CarySwoveland指令在代码中,但基本上是的,它会将“abcde”转换为“ace”。
“hello”。chars.each_slice(2)。map(&:first)。join#=>“hlo”
是另一种方式。这里不是使用拆分的方式。我明白了,通过将字符串[idx]推到final,并返回预期的输出,您是否会在@Sergio创建一个答案?不,我在评论中暗示了这一点。我在这里的工作完成了:)“你在“转换”数组中的字母”-这不是问题,顺便说一句:)多个数组的串联工作。使用
'a'.split#=>['a']
,和
'.split#=>[]
,所以没有空格可以连接,不是吗?,怎么样?