Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 599 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to check if a specific key is present in a hash or not?

#1
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" *key* is present.
Reply

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

session.key?("user")
Reply

#3
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.

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

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

If not it will return you `false`

hash = { one: 1, two:2 }

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

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

#5
While `Hash#has_key?` gets the job done, as Matz notes [here](

[To see links please register here]

), it has been deprecated in favour of `Hash#key?`.

hash.key?(some_key)
Reply

#6
Another way is here

hash = {one: 1, two: 2}

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

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

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

YourHash.has_key? :yourkey
Reply

#8
Hash instance has a [`key?`][1] method:

{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

[1]:

[To see links please register here]

Reply

#9
```
h = {}
if h.respond_to?(:key?) && h.key?('text') #with respond_to method check if it's hash
puts h['text']
end
```
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through