cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

TIP: (Safely) Concatenating Strings that might be NULL

RussellJ
Deputy Chef III
Deputy Chef III

I was today years old when I came across this simple solution so thought I'd post it!

I often find I want to concatenate two or more strings together, usually when trying to formulate a friendly error message for a log or an email to a human when something's not quite worked right.

However, you can't safely just use...

no conv.jpg

... because if either or both values contains a NULL, Workato throws an error.

I started to head down the ternary operator route (which felt overly complicated and difficult to read) and then stumbled across the use of ".to_s" for each data pill to force convert the data pill to a string...

to_s.jpg

Now, if either value contains NULL the result is an empty string (which Workato is then happy to "squish" with another string).

Realise it's very basic, but thought I'd share in case someone else might find it useful.

Tune in next week for "Russell learns to pat his head and rub his tummy at the same time"...

[waits for @gary1  to jump in with an even better, more elegant solution...]

3 REPLIES 3

gary1
Star Chef I
Star Chef I

This is actually pretty interesting. I figured .to_s would error out on nil.

My preferred way is:

[$string1, $string2].smart_join("") ## use any delimiter you want

## the above is essentially the same as the below
[$string1, $string2].compact.join("")

 

RussellJ
Deputy Chef III
Deputy Chef III

{faints}

I did consider smart_join but prefer the really clean .to_s, but hadn't come across compact before - thanks!

I might start reading an alphabetical list of workato allowed functions in case there's anything else of interest (after all that's how I first learned BASIC on my ZX81... the manual for which someone has kindly made available online ๐Ÿ˜).

Happy Friday.

gary1
Star Chef I
Star Chef I

Oh, I almost forgot the safety operator. When you have a variable that might be nil, you can use the safety operator (&) to skip calling the method entirely. I use this on pretty much every inline Ruby I write these days.

## bad news bears
array = nil
nil.where(x: true) ## error, no method .where for nil

## safety operator &
array = nil
nil&.where(x: true) ## returns null, no error