我试图在红宝石句子中隔离白色空间

问题描述 投票:-1回答:2

我试图将一个字符串的所有字符放在一个数组中它自己的索引中,并且我也试图用0代替" "(空格)。我得到的错误是说的

?错误的参数数量(给定0,预期1)

但我不知道如何让include(' ')工作。

这是我的代码:

def findMe(words)
  x = 0
  convert = []

  while x < words.length
    if words[x].is_a? String && words[x].include? != " "
      convert << words[x]
    else
      convert << 0
    end
    x = x + 1
  end

  p convert

end

findMe('Words and stuff.')

期望的输出:["W", "o", "r", "d", "s", 0, "a", "n", "d", 0, "s", "t", "u", "f", "f", "."]

arrays ruby include
2个回答
4
投票

你在这里得到“错误的参数数量”错误:

words[x].include? != " "

您可以通过以下代码快速解决此问题:

!words[x] == " "

做整件事的更好方法是:

words.gsub(" ", "0").chars

0
投票

使用Array#chars

'Words and stuff.'.chars.map { |c| c ==  " " ? "0" : c }
 #=> ["W", "o", "r", "d", "s", "0", "a", "n", "d", "0", "s", "t", "u", "f", "f", "."]
© www.soinside.com 2019 - 2024. All rights reserved.