Ruby-on-rails 如何检查特定键是否存在于哈希中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4528506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:58:33  来源:igfitidea点击:

How to check if a specific key is present in a hash or not?

ruby-on-railsrubydata-structuresassociative-array

提问by Mohit Jain

I want to check whether the "user" key is present or not in the session hash. How can I do this?

我想检查会话哈希中是否存在“用户”键。我怎样才能做到这一点?

Note that I don't want to check whether the key's value is nil or not. I just want to check whether the "user" keyis present.

请注意,我不想检查键的值是否为 nil。我只想检查“用户”是否存在。

回答by sepp2k

Hash's key?method tells you whether a given key is present or not.

Hashkey?方法告诉您给定的键是否存在。

session.key?("user")

回答by Bozhidar Batsov

While Hash#has_key?gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?.

Hash#has_key?完成工作的同时,正如 Matz在此处指出的那样,它已被弃用,而支持Hash#key?.

hash.key?(some_key)

回答by installero

In latest Ruby versions Hash instance has a key?method:

在最新的 Ruby 版本中,Hash 实例有一个key?方法:

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

Be sure to use the symbol key or a string key depending on what you have in your hash:

请务必使用符号键或字符串键,具体取决于哈希中的内容:

{'a' => 2}.key?(:a)
=> false

回答by G.B

It is very late but preferably symbols should be used as key:

很晚了,但最好使用符号作为键:

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 

But when creating hash if you pass string as key then it will search for the string in keys.

但是在创建哈希时,如果您将字符串作为键传递,那么它将在键中搜索字符串。

But when creating hash you pass symbol as key then has_key? will search the keys by using symbol.

但是在创建哈希时,您将符号作为键传递,然后是 has_key?将使用符号搜索键。



If you are using Rails, you can use Hash#with_indifferent_accessto avoid this; both hash[:my_key]and hash["my_key"]will point to the same record

如果您使用的是 Rails,则可以使用Hash#with_indifferent_access来避免这种情况;双方hash[:my_key]hash["my_key"]会指向相同的记录

回答by Deepak Mahakale

You can always use Hash#key?to check if the key is present in a hash or not.

您始终可以使用Hash#key?来检查密钥是否存在于散列中。

If not it will return you false

如果没有它会返回你 false

hash =  { one: 1, two:2 }

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

hash.key?(:four)
#=> false

回答by Arvind singh

Another way is here

另一种方式在这里

hash = {one: 1, two: 2}

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

hash.member?(:five)
#=> false

回答by BinaryMan

In Rails 5, the has_key?method checks if key exists in hash. The syntax to use it is:

在 Rails 5 中,has_key? 方法检查哈希中是否存在键。使用它的语法是:

YourHash.has_key? :yourkey