From: Phrogz Date: 2007-06-16T06:30:10+09:00 Subject: Re: test to see if a variable exists On Jun 15, 2:36 pm, "Colin Summers" wrote: > So I am stealing all these identities and storing everything in a big > array of objects stolen_identity, and having the index be social > security numbers: > > ss[34323843] = Stolen_identity.new > > But say I pick up a paycheck stub and it has 3428294. How do I know if > I already have it? Does > if (exist ss[3428294]) then ... end > work? How can I see if a variable exists? Arrays (and Hashes) in Ruby are sparse - they only store the values you actually enter. However, there are some limitations on the size of indices for arrays: C:\>irb irb(main):001:0> ss = [] => [] irb(main):002:0> ss[ 884_56_2103 ] = "I HAVE YOU NOW" ArgumentError: index too big from (irb):2:in `[]=' from (irb):2 So, you probably want to use a Hash, which has no such limitation. With both Arrays and Hashes, supplying a key or index which has no stored value will return a nil object: irb(main):003:0> ss = {} => {} irb(main):004:0> ss[ 884_56_2103 ] = "I HAVE YOU NOW" => "I HAVE YOU NOW" irb(main):005:0> ss[ 912_34_3552 ] => nil In Ruby, nil and false are both non-truth values for the purposes of boolean logic. Additionally (and slightly more cleanly), you can ask a Hash directly if it has an entry for a specific key: irb(main):006:0> if ss.has_key?( 884_56_2103 ) then irb(main):007:1* puts "I'm done with this guy" irb(main):008:1> else irb(main):009:1* puts "Sweet new information!" irb(main):010:1> end I'm done with this guy