Ruby无法在For循环中将数组转换为整数

时间:2014-09-21 12:09:35

标签: ruby arrays

我正在尝试获取一个哈希数组(称为哈希),我将根据输入行中的单词是否在某些数组中来填充布尔值。为了正确看待这一点,我正在进行一系列输入,并扫描它以查看该输入中的单词是否在我设置的一系列数组中。

11: for i in words
12:    if nouns.include?(words[i])
13:        hashes[i][:nouns] = true
14:    end 
15:
16:    if adjectives.include?(words[i])
17:        hashes[i][:adjectives] = true
18:    end 
19: end

第12行的错误,在`[]'中说Analyzer.rb:12:无法将Array转换为Integer(TypeError)

我觉得我刚刚在某个地方犯了一个愚蠢的格式化错误,但我看不到它。有什么建议?提前谢谢。

3 个答案:

答案 0 :(得分:4)

11: for word in words
12:    if nouns.include?(word)
13:        hashes[word][:nouns] = true
14:    end 
15:
16:    if adjectives.include?(word)
17:        hashes[word][:adjectives] = true
18:    end 
19: end

word,之前是i(我给它一个更好的名字),实际上已经是数组的元素,而不是索引。

答案 1 :(得分:1)

您应该尝试使用rubys强大的可枚举编码样式来避免此类错误。因为循环不像红宝石。

您的代码可以写成:

11: words.each_with_index do |word, i|
12:    
13:    hashes[i][:nouns] = true if nouns.include?(word)   
14:    hashes[i][:adjectives] = true if adjectives.include?(word)
15:
16: end

答案 2 :(得分:0)

最好为您的数组使用methdo each_index 。 但是,如果您想使用 for 进行数组尝试将word [i]更改为word。 for 使用对象操作但不使用索引。 Nicola Miotto为你的例子编写了代码。