返回nil而不是undefined方法`[]’用于nil:NilClass,当有一个对象数组时。

huangapple go评论59阅读模式
英文:

Return nil instead of undefined method `[]' for nil:NilClass when having array of objects

问题

我有以下的 @params,其中 people 是一个对象数组。
{"people"=>[{"email"=>"sample1@google.com"}, {"email"=>"sample@google.com"}]}

当我尝试访问 @params[:people][0][:email] 时,如果任何电子邮件或人员不存在,或者如果 @params[:people] 有一个空数组并且我们尝试获取电子邮件时,我想要得到 nil 而不是未定义方法'[]'的错误,用于nil:NilClass。

我发现我们可以使用 @params.dig(:people),但我想知道如何考虑数组 [0] 并实现这一点。

英文:

I have the following @params where people is an array of objects.
{"people"=>[{"email"=>"sample1@google.com"}, {"email"=>"sample@google.com"}]}

I am looking for a way to get back nil instead of the undefined method '[]' for nil:NilClass error when I try to access @params[:people][0][:email] when any of the emails or people are not present or if @params[:people] has an empty array and we try to get the email.

I found that we could use @params.dig(:people) but I would like to know how I can consider the array [0] and achieve this?

答案1

得分: 2

以下是翻译好的部分:

@params.dig(:people, 0, :email)

示例:

params = { people: [{ email: 'foo@example.com' }] }
params.dig(:people, 0, :email)
# => "foo@example.com"

params = { people: [] }
params.dig(:people, 0, :email)
# => nil
英文:

The following will do the job:

@params.dig(:people, 0, :email)

Example:

params = { people: [{ email: 'foo@example.com' }] }
params.dig(:people, 0, :email)
#=> "foo@example.com"

params = { people: [] }
params.dig(:people, 0, :email)
#=> nil  

huangapple
  • 本文由 发表于 2023年3月9日 16:48:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定