aerijman
aerijman

Reputation: 2762

hash.key(my_key) not accessing keys in nested hash in ruby

1- I have little experience in ruby and I am coming from C/Python.

2- In the following snippet:

CSV.foreach(filename, quote_char: '"', col_sep: "\t") do |row|
    if header_seen == true
        k = row[primer]
        c = row[counts].to_i
        p = row[prfreq].to_f
        e = row[err].to_f

        print k," ",table.keys," ",table,"\n"

        if table.key(k) == true
            table[k]['counts'] << c
            table[k]['err'] << e
            table[k]['prfreq'] << p
        else
            puts "WHY IT IS ALWAYS GETTING HERE???"
            table[k] = {'counts'=>[c], 
                        'err'=>[e],
                        'prfreq' => [p]
                    }
        end

    elsif header_seen == false and row[0] == "BARCODE"
        counts  = row.index('PRCOUNT')
        primer = row.index('PRIMER')
        prfreq = row.index('PRFREQ')
        err = row.index('ERROR')
        header_seen = true
    end 
end

Printing table.keys (line 8), I can see the keys. However, if table.key(k) == true never comes true.

What am I doing wrong?

Upvotes: 0

Views: 48

Answers (2)

user1934428
user1934428

Reputation: 22217

Assuming that table is a Hash (which we don't know for sure from your code), table.key(k) returns the value for the key k, if the key exists in your hash, or nil if it does not. Since the values of your Hash are seemingly not boolean values, the comparision with true will always be false.

If you just want to test, whether the key exists, use the method key? instead of key:

if table.key?(k)
   ...
end

(explicit comparision with true could be done in this case, but is redundant, so I left it out).

If your Hash has been constructed to use the standard value for it's default value (i.e. nil), you can shorten this to

if table[k]
    ...
end

The main difference between table.key(k) and table[k] is that if k is missing in the Hash, the former always returns nil, while the latter returns the default value for this particular Hash which you provided in the constructor.

See here for details.

Upvotes: 3

aerijman
aerijman

Reputation: 2762

It should be table.key?(k) instead of table.key(k)

Upvotes: 2

Related Questions