英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论