Assigning a replacement value in the case of nil

I have a few variables:

name age address phone social_security email weight 

And an array called personal_details with each of these values ​​at positions 0-6.

So, I assign such values:

 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, data on the right side does not exist.

What a more elegant way to handle this than writing something like this for each element of 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 
+4
source share
3 answers

You can do this because nil returns false and || will evaluate only the right side if the left side is false:

 name = personal_details[0] || '' 
+11
source
 name = personal_details[0] || "" 
+2
source

Update: This is not correct, see discussion below.

There is a built-in way to do this with 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, '') 

Other solutions will work just fine based on the example you provided. If one of the values ​​on the right side is set to false , the approach || will return an empty string instead of a value.

+1
source

All Articles