I have a few variables:
name
age
address
phone
social_security
email
weight
And an array called personal_details
with each of these values in positions 0-6.
So I assign values like this:
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]
In some cases, however, the data on the right hand side does not exist.
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
You could do this since a nil
value returns false and ||
will only evaluate the right-hand side if the left-hand side is false:
name = personal_details[0] || ''
name = personal_details[0] || ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With