2011-06-05 44 views
0

我有此数组:查询对象不存在

--- !map:ActiveSupport::HashWithIndifferentAccess 
search: !map:ActiveSupport::HashWithIndifferentAccess 
    address: test 

我申请以下它:

address = params['search']['address'] 
if address 
    # do something 
end 

如果没有搜索对象,也没有地址对象,代码产生了一个错误:

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.[]

在ruby中处理类似的东西的方式是什么?

+0

作为JITS所指出的,你可能有一个数组。在ruby中评论不是'//',它是'#'。我修好了它。 – sawa 2011-06-05 22:15:33

+0

谢谢sawa。 – choise 2011-06-06 08:38:02

回答

2

首先...

[...] for example i have this array:

只是为了澄清,它实际上是一个专门Hash

其次...

你可以做这样的事情:

if params[:search] and params[:search][:address] 
    # do something with address 
else 
    # no value given 
end 
+0

谢谢,你是对的。为什么'params ['search'] ['address']'为散列工作? – choise 2011-06-06 08:39:00

+0

@choise,它是一种特殊的散列,可以将字符串或符号作为关键字并将其视为相同。 – Jits 2011-06-06 08:58:12