看不清为什么我“没有从nil到整数的隐式转换”错误

时间:2017-06-07 05:00:59

标签: ruby

嘿伙计们我遇到了这个问题。我正在用书做练习,这就是其中之一。

拼写块的集合每个块有两个字母,如下表所示:

B:O   X:K   D:Q   C:P   N:A
G:T   R:E   F:S   J:W   H:U
V:I   L:Y   Z:M

这可以将您使用块拼写的单词限制为不使用任何给定块中的两个字母的单词。每个块只能使用一次。

编写一个方法,如果作为参数传入的单词可以从这组块中拼写,则返回true,否则返回false。

示例:

block_word?('BATCH') == true
block_word?('BUTCH') == false
block_word?('jest') == true

这是我尝试解决方案。我正在从文本文档中阅读该集合。

  text = []
    File.open('example2.txt').each { |line| text << line }
    @pair1 = []
    @pair2 = []
    text.join('').split('   ').each {|x, i| @pair1 << x[0].to_s; @pair2 << x[2].to_s}

    def block_word?(word)
      word = word.upcase
      @pair1.map {|x, i| word.include?(x) && word.include?(@pair2[i]) }.include?(true)
    end

    block_word?('BATCH') == true
    block_word?('BUTCH') == false
    block_word?('jest') == true

我收到了这个错误。不知道为什么。

rb2.rb:10:in `[]': no implicit conversion from nil to integer (TypeError)
        from rb2.rb:10:in `block in block_word?'
        from rb2.rb:10:in `map'
        from rb2.rb:10:in `block_word?'
        from rb2.rb:13:in `<main>'

2 个答案:

答案 0 :(得分:0)

引发此错误,因为您尝试使用@pair2索引访问数组nilmap方法不会将索引作为提供块的第二个参数发送。要添加它们,您可以在each_with_index之前添加map方法。另请参阅此question

@pair1.each_with_index
   .map{ |x, i| word.include?(x) && word.include?(@pair2[i]) }
   .include?(true)

试试这段代码,它将有助于了解发生了什么:

pair2 = []
puts pair2[nil] # will raise the same exception

答案 1 :(得分:0)

您的索引i为零,因为您只执行map仅迭代元素,使用mapindex您需要使用{{1}如文档中所示,它将为您提供元素.map.with_index和索引x

i