Home > Enterprise >  Have anyone found beautiful way to replace "smth if smth.present?"?
Have anyone found beautiful way to replace "smth if smth.present?"?

Time:08-02

Often I'm facing lines like

result = 'Some text'
result  = some_text_variable if some_text_variable.present?

And every time I want to replace that with something more accurate but I don't know how

Any ideas plz?

CodePudding user response:

result  = some_text_variable.to_s

It will work if some_text_variable is nil or empty string for example

But it always will concat empty string to original string

You can also use

result  = some_text_variable.presence.to_s

It will work for all presence cases (for example for " " string)

CodePudding user response:

You could "compact" and join an array, e.g.

['Some text', some_text_variable].select(&:present?).join

I realise this is a longhand form, just offering as an alternative to mutating strings.

This can look a bit nicer, if you have a large number of variables to munge together, or you want to join them in some other way e.g.

[
  var_1, 
  var_2,
  var_3,
  var_4
].select(&:present?).join("\n")

Again, nothing gets mutated - which may or may not suit your coding style.

  • Related