One of common thing that any programs do is concatenate two or more String value, e.g.
first_name = 'huy'
sir_name = 'le'
name = first_name + ' ' + sir_name # huy le
But the above code suffers a problem, if one of concatenated variables is
nil
, then it will not work. Checking
nil
is tedious and error prone, a simple solution of this problem is putting concatenated variables into an array, removing nil using
compact
and using
join
method to perform concatenation.
first_name= 'huy'
middle_name=nil
sir_name = 'le'
name = [first_name, middle_name, sir_name].compact.join(' ') # huy le
No comments:
Post a Comment