Cómo comprobar si una clave específica está presente en un hash o no?


Quiero comprobar si la clave "user" está presente o no en el hash de la sesión. ¿Cómo puedo hacer esto?

Tenga en cuenta que no quiero comprobar si el valor de la clave es nil o no. Solo quiero comprobar si la tecla" user " está presente.

Author: jaysoifer, 2010-12-25

5 answers

Hash's key? método le dice si una clave dada está presente o no.

session.key?("user")
 783
Author: sepp2k,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-08 21:32:34

Mientras que Hash#has_key? hace el trabajo, como Matz señala aquí, ha sido obsoleto a favor de Hash#key?.

hash.key?(some_key)
 259
Author: Bozhidar Batsov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-12 19:44:53

En las últimas versiones de Ruby, la instancia Hash tiene key? método:

{a: 1}.key?(:a)
=> true

Asegúrese de usar la tecla symbol o una tecla string dependiendo de lo que tenga en su hash:

{'a' => 2}.key?(:a)
=> false
 30
Author: installero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-25 18:39:29

Es muy tarde, pero preferiblemente se deben usar símbolos como clave:

my_hash = {}
my_hash[:my_key] = 'value'

my_hash.has_key?("my_key")
 => false 
my_hash.has_key?("my_key".to_sym)
 => true 

my_hash2 = {}
my_hash2['my_key'] = 'value'

my_hash2.has_key?("my_key")
 => true 
my_hash2.has_key?("my_key".to_sym)
 => false 

Pero al crear hash si pasa cadena como clave, entonces buscará la cadena en claves.

Pero cuando se crea hash se pasa el símbolo como clave entonces has_key? buscará las llaves usando el símbolo.


Si está utilizando Rails, puede usar Hash#with_indifferent_access para evitar esto; tanto hash[:my_key] como hash["my_key"] apuntarán al mismo registro

 26
Author: G.B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-25 18:38:51

Siempre puede usar Hash#key? para verificar si la clave está presente en un hash o no.

Si no, te devolverá false

hash =  { one: 1, two:2 }

hash.key?(:one)
#=> true

hash.key?(:four)
#=> false
 4
Author: Deepak Mahakale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-14 16:13:34