17

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 

2 Answers 2

35

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

try this:

e.has_key? :uid 
Sign up to request clarification or add additional context in comments.

5 Comments

If all you have is a string, you could also "uid".to_sym
"has_key" not defined, but "to_sym" is helpful. Thanks.
has_key? -be aware of the question mark- is a method of any instance of Hash class. It can not be undefined unless you're using it something different than a Hash instance.
That's why I puzzled, I don't know what it is. I end up using "entry.each do |k, v|" to break into key-value pair.
It's as simple as adding a .class to any object to know it's class type. Do a e.class and you'll see what it is.
6

The key "uid" doesn't exist. Try

e = Entry.new.myhash e.has_key?(:uid) 

That should return true. If that gives you an error, the problem might lie in your class. Make sure that myhash is defined in the initialize method, and that you use a getter method (or attr_reader) to be able to access the variable. You could use

attr_reader :myhash 

right before the initialize method.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.