tags:

views:

53

answers:

2

I'm using Watir and Ruby to try and slurp a load of data from a web application into a hash:

def getOrders( )

    return orders = slurpOrders()

end

def containsOrderNumber( orderNumber )
    puts orderNumber 
    orders = getOrders
    puts orders[orderNumber]
    #puts orders.keys

    puts "orders has_key? = " + orders.has_key?(orderNumber).to_s
    return orders.has_key?(orderNumber)

end

private
def slurpOrders( ) 

    puts @browser.tables[6].row_count

    rows = @browser.tables[6].rows

    orders = Hash.new

    for row in rows do
        #puts row.column_count
        if row.column_count == 8 then
            order = {
                :sales_channel => row[2],
                :customer => row[3],
                :country => row[4],
                :total => row[5],
                :time => row[6],
                :highlight => row[7],
                :credit_hold => row[8],
            }
            orders[ row[1] ] = order

            #puts row[1]

        end
    end

    return orders

end

So I'm calling containsOrderNumber( '1136050' ) in another script but orders.has_key? returns false and orders[orderNumber] returns nil.

However, if I uncomment puts orders.keys, it appears as one of the keys in the hash...? I'm super confused - what am I doing wrong? Is something weird happening data-type-wise?

Cheers

+2  A: 

It seems you are storing the key as integer and trying to retrieve it as a string. You just need to be consistent (and either add conversion to a string when storing, or a conversion to an int when retrieving).

mb14
+2  A: 

When you're doing printf debugging, make sure you don't use

puts orders.keys

but use

puts orders.keys.inspect

as inspect will allow you to differentiate between integers and strings:

hash = {"1" => :string, 2 => :integer}
puts hash.keys # Outputs 1(newline)2(newline)
puts hash.keys.inspect # Outputs ["1", 2](newline)
Andrew Grimm