首页>Program>source

我有几个变量:

name
age
address
phone
social_security
email
weight

还有一个名为 personal_details的数组 这些值分别位于0-6位。

所以我分配这样的值:

name = personal_details[0]
address = personal_details[1]
phone = personal_details[2]
social_security = personal_details[3]
email = personal_details[4]
weight = personal_details[5]

但是,在某些情况下,右侧的数据不存在。

What's a more elegant way to handle this than writing something like this for each element in the array?

if !personal_detail[0].nil?
 name = personal_details[0]
else
 name = ""
end
if !personal_detail[1].nil?
 address = personal_details[1]
else
 address = ""
end
最新回答
  • 10天前
    1 #

    由于 nil,您可以执行此操作 值返回false和 || 仅当左侧为false时,才会评估右侧:

    name = personal_details[0] || ''
    

  • 10天前
    2 #

    name = personal_details[0] || ""
    

  • 10天前
    3 #

    Update: 这是不正确的,请参见下面的讨论。

    使用Array#fetch有一种内置方法:

    personal_details = ['Joe User', nil, '12 Main Street']
    name    = personal_details.fetch(0, '')
    age     = personal_details.fetch(1, '')
    address = personal_details.fetch(2, '')
    

    其他解决方案将根据您提供的示例正常运行.如果右侧的值之一设置为 false|| 方法将返回空字符串而不是值。

  • casting:R浮点数精度在字符覆盖范围内丢失
  • jQuery Mobile:单击按钮时如何不显示按钮焦点光晕?