Ninjinx
Ninjinx

Reputation: 645

Prevent conditional checking on Hash to create Key

Whenever I run a conditional checking on Hash to see if a key doesn't have any value, it creates that key

x = Hash.new {|h,k| h[k] = []}
puts x
>>>>{}


if x[0] == []
    puts "Ok"
end

>>>>Ok

puts x
>>>> {0=>[]}

How do I prevent this?

Upvotes: 0

Views: 36

Answers (2)

pangpang
pangpang

Reputation: 8821

x = Hash.new {|h,k| h[k] = []}

if you create hash like this, it will set a new default object each time.

for example:

x = Hash.new {|h,k| h[k] = 0}

x[0]
=> 0
x
=> {0=>0}

x = Hash.new {|h,k| h[k] =  "a" }
=> {}

x[0]
=> "a"
x
=> {0=>"a"}

so you should know what default hash value do you want.

Upvotes: 0

spickermann
spickermann

Reputation: 106972

You could use the has_key? method:

x = Hash.new { |h,k| h[k] = [] }

x.has_key?(0)
#=> false
x
#=> {}

Saying that you could change your condition to:

puts "Ok" if x.has_key?(0) && x[0] == []

That means you will only check the value for x[0] if you alreday know that the key exists.

Upvotes: 1

Related Questions