如何从存储在ruby哈希中的数组中删除特定值

时间:2014-03-18 19:40:16

标签: ruby arrays hashset

我在错误列表中得到了这个:

@error_messages = {
                   :password=>["can't be blank", "Password is required."], 
                   :"addresses.firstname"=>["can't be blank","Firstname is required."],
                   :"addresses.city"=>["can't be blank", "city is required."]
                  }

这里我想从此哈希中删除值“不能为空”值,以便获取我包含的验证错误消息。

是否可以从上面的哈希列表中删除“不能为空”值,我会得到结果:

       @error_messages = {
                          :password=>["Password is required."],
                          :"addresses.firstname"=>["Firstname is required."],
                          :"addresses.city"=>["city is required."]
                         }

如何从哈希列表中删除特定值(想要删除特定值而不是完整的键,值对)。

1 个答案:

答案 0 :(得分:4)

是的,可能。

@error_messages = {
                   :password=>["can't be blank", "Password is required."], 
                   :"addresses.firstname"=>["can't be blank","Firstname is required."],
                   :"addresses.city"=>["can't be blank", "city is required."]
                  }

@error_messages.each do |_,v|
   v.delete( "can't be blank" )
end

@error_messages
# => {:password=>["Password is required."],
#     :"addresses.firstname"=>["Firstname is required."],
#     :"addresses.city"=>["city is required."]}