0

I'm trying to get an array of hashes (called hashes) which I will proceed to fill with booleans based on whether or not a word in a line of input is in some arrays. To put this into perspective, I'm taking a line of input, and scanning it to see if the words in that input are inside a series of arrays I have set up.

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

This errors on line 12, saying Analyzer.rb:12 in `[]': can't convert Array into Integer (TypeError)

I get the feeling I've just made a silly formatting error somewhere, but I can't see it. Any Suggestions? Thank you in advance.

1
  • 3
    What is the content of words? Commented Sep 21, 2014 at 12:11

3 Answers 3

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, that was i before (I gave it a better name), is actually already an element of the array, not an index.

Sign up to request clarification or add additional context in comments.

1 Comment

In your answer you try to access the hashes array with the object word by it's [] method. This should only work if word is an integer, but should fail if it's a String (or anything else). Why does this work perfectly? Looks like a flawed answer to me.
2

You should try using rubys powerful enumerable style of coding to avoid such errors. For loops are not ruby like.

Your code could be written as:

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 Comments

There is no index in OP's code, only a badly named variable i.
he said it's an array of hashes called "hashes". So he wanted to access the array by index? It confues me that Nicola Miotto's answer works perfectly, as arrays [] method requires an index or a range, not an object. If word is a string it would work if hashes is a Hash not a Array
0

Better to use methdo each_index for your array. But if you want to use for for array try to change word[i] to word. for operate with object but not with index. Nicola Miotto wrote code for your example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.