如何检查 Ruby 哈希中是否存在键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22649548/
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
How to check if a key exists in a Ruby hash?
提问by user180574
I am using search of Net::LDAP, the returned entry is something like this.
我正在使用 Net::LDAP 搜索,返回的条目是这样的。
#<Net::LDAP::Entry:0x7f47a6491c00
@myhash=
{:loginshell=>["/bin/bash"],
:cn=>["M... R..."],
:homedirectory=>["/mnt/home/m..."],
:uid=>["m..."],
:userpassword=>["{CRYPT}zR/C...$R1"],
...
}>
I tried to do the following, but failed.
我尝试执行以下操作,但失败了。
(1)
(1)
e = entry.to_hash
e.has_key? "uid"
(2)
(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.
第一个错误表示“to_hash”未定义,第二个“has_key”未定义。然后我真的不知道该怎么做,基本上我想找到“uid”是否存在,如果存在,则获取其对应的值。
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,
顺便说一句,它只响应“entry.uid”,但如果搜索键是作为字符串提供的,该怎么做?例如,
def get_value(key)
if entry has key
return key's value
end
end
回答by scaryguy
:uidis a Symbol. That's not a String.
:uid是一个Symbol。那不是String.
try this:
尝试这个:
e.has_key? :uid
回答by JordanD
The key "uid" doesn't exist. Try
键“uid”不存在。尝试
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
那应该返回true。如果这给您带来错误,则问题可能出在您的班级中。确保在 initialize 方法中定义了 myhash,并且您使用 getter 方法(或 attr_reader)能够访问该变量。你可以用
attr_reader :myhash
right before the initialize method.
就在 initialize 方法之前。

