1

I have a function in Ruby:

def find_item(keyword)
    potential = []
    $items.each do |item|
        puts item                                 # <-- for debugging purposes
        if item["name"].downcase== keyword
            potential << item["name"].downcase
        elsif item["keywords"].index(keyword) != nil
            potential << item["name"].downcase
        end
    end
    return potential
end

(The global variable $items is a Hash object that maps a few strings to some values that determine the properties of the item.)

When I puts the current item it is iterating over (the line with the comment does just that), it gives me:

{"name"=>"Thing1", "keywords"=>["thing", "green"], ...}

but when I try item["name"] on the next line (which should definitely return Thing1), it gives me:

C:/somepath/someprogram.rb:125:in '[]': can't convert String into Integer (TypeError)

0

1 Answer 1

2

if $items is a Hash, then $items.each do |item| will yield [key, value] pairs (Arrays) to the block. If you only want the values, use each_value.

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

3 Comments

And if you need both key and value, use destructuring bind.
In case "destructuring bind" is unknown to you (I myself never heard it in the Ruby community), he means doing something like $items.each do |key, value|
Ahh ok that seems to be the problem :) Thanks!

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.