lundi 4 janvier 2021

times method returns nil with hash

What I did is get random 2 values from hash and match them with the keys. My code gets two random values, that part works well. But when it comes to p hash[m], I expected it would print the key of hash, instead it returns nil. For example :

Our random values are "cat" and "ocean". The program pick this values by itself with times method.

So when m = "cat" hash[m] should be "dog", but it's nil. The same thing goes for "ocean" too. So I have two nil values. Why? How can I fix that and get the right key?

hash = { "foo" => "bar", "cat" => "dog", "ear" => "nose", "ocean" => "sea"}
value = hash.values

2.times do 
  m = value[rand(value.size)]
  p hash[m] #Erroneous part
end



Aucun commentaire:

Enregistrer un commentaire