Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a key exists in a Ruby hash?

Tags:

ruby

I am using search of Net::LDAP, the returned entry is something like this.

#<Net::LDAP::Entry:0x7f47a6491c00
 @myhash=
  {:loginshell=>["/bin/bash"],
   :cn=>["M... R..."],
   :homedirectory=>["/mnt/home/m..."],
   :uid=>["m..."],
   :userpassword=>["{CRYPT}$1$3zR/C...$R1"],
   ...
}>

I tried to do the following, but failed.

(1)

e = entry.to_hash
e.has_key? "uid" 

(2)

entry.has_key? "uid" 

The first error says "to_hash" undefined, the second "has_key" undefined. Then I really don't know how to do it, basically I want to find if "uid" is present and if so get its correspondent value.

Thank you very much for the tip.

BTW, it only responds to "entry.uid", but if the search key is provided as a string, how to do that? for example,

def get_value(key)
  if entry has key 
    return key's value
  end
end
like image 763
user180574 Avatar asked Mar 26 '14 01:03

user180574


People also ask

How can you tell if a value is present in a hash?

Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .

How do I get the hash key in Ruby?

You can find a key that leads to a certain value with Hash#key . If you are using a Ruby earlier than 1.9, you can use Hash#index . Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera.

Is Ruby a Hash?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.


1 Answers

:uid is a Symbol. That's not a String.

try this:

e.has_key? :uid
like image 168
scaryguy Avatar answered Oct 22 '22 19:10

scaryguy