Ruby 1.9.2 不存在的哈希元素
我使用的是 Rails 3.0.x、Ruby 1.9.2,需要一种方法来测试可能存在或不存在的参数,例如,
params[:user] #exists
params[:user][:login] #may not exist
第二次检查的正确 Ruby 语法是什么,这样它就不会呕吐?
I'm on Rails 3.0.x, Ruby 1.9.2 and needs a way to test for params that may or may not exists, e.g.,
params[:user] #exists
params[:user][:login] #may not exist
What's the proper Ruby syntax for the 2nd check so it doesn't barf?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试以下操作:
Try following:
@WarHog 说得很对。
params
中的项目有时返回字符串,有时返回哈希,这是非常不寻常的,但无论如何您都可以轻松处理:而不是
respond_to? :has_key?
你也可以respond_to? :[]
还是只是is_a?哈希
。主要是偏好问题。@WarHog has it right, pretty much. It's very unusual for an item in
params
to sometimes return a string but other times return a Hash, but regardless you can handle that easily enough:Instead of
respond_to? :has_key?
you could also dorespond_to? :[]
or justis_a? Hash
. Mostly a matter of preference.在第二种情况下你只会得到零..这应该不是问题,不是吗?
例如,
params[:user][:login]
仅返回 nil,如果 :user 条目存在于第一个哈希中,则计算结果为 false。但是,如果嵌套更深一层或多层,并且丢失的哈希条目位于中间的某个位置,则会遇到问题。例如:
在这种情况下,Ruby 会尝试评估 nil[:something] 并引发异常,
你可以这样做:
...你可以进一步抽象...
You would just get nil in the second case.. that shouldn't be a problem, no?
e.g.
params[:user][:login]
just returns nil, which evaluates to false if the :user entry exists in the first Hash.However if the nesting would be one or more levels deeper, and the missing hash entry was somewhere in the middle, you would have problems. e.g.:
in that case Ruby would try to evaluate nil[:something] and raise an exception
you could do something like this:
... which you could further abstract...