Checking for nil string before concatenating

Viewed 15639

This question is similar to a LOT of questions, but in no such way is it anything of a duplicate. This question is about string concatenation and writing better code less than it is for checking nil/zero.

Currently I have:

file.puts "cn: " + (var1.nil? ? "UNKNOWN" : var1)

Which works fine, but doesn't look good. What is a better way to write this in ruby so that I am checking for nil and not concatenating it

6 Answers

You can do this:

file.puts "cn: " + (var1 || "UNKNOWN")

or, identically if you prefer:

file.puts "cn: " + (var1 or "UNKNOWN")

or my favourite, which I think is the most idiomatic ruby:

file.puts "cn: #{var1 or 'unknown'}"

I would do what Peter suggested, assuming that false wasn't a valid value for var1, and var1 was guaranteed to be nil or a string. You could also extract that logic into a function:

def display_value(var)
  (var || "UNKNOWN").to_s # or (var.nil? ? "UNKNOWN" : var.to_s) if 'false' is a valid value
end

file.puts "cn: " + display_value(var1)

to_s is only necessary if var1 isn't guaranteed to be nil or a string. Alternatively, if you do:

file.puts "cn: #{display_value(var1)}"

it will do an implicit to_s on the result of display_value

file.puts( "cn:" + (var1 || "UNKNOWN" ))
Related