我试图用红宝石句子隔离空白

时间:2018-03-03 20:23:32

标签: arrays ruby include

我试图将字符串中的所有字符放入数组中自己的索引中,并尝试将" "(空格)替换为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", "."]

2 个答案:

答案 0 :(得分:4)

你得到的错误数量的参数&#34;错误在这里:

class DataController1: NSObject, DataController {

    struct Section {
        let type: SectionTypeEnum
        let rows: [Any]
    }

    let contactData: ContactData
    var section1: [Section1]
    var section2: [Section2]
    var section3: [Section3]
    var sections: [Section]


    init(contactData: ContactData) {
        self.contactData = contactData

        section1 = self.contactData.list1
        section2 = self.contactData.list2
        section3 = self.contactData.list3
        sections = [Section(type: .section1, rows: section1),
                    Section(type: .section2, rows: section2),
                    Section(type: .section3, rows: section3)]
    }
}

您可以通过以下方式快速解决此问题:

words[x].include? != " "

完成整个事情的更好方法是:

!words[x] == " "

答案 1 :(得分: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", "."]