Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for nil string before concatenating

Tags:

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

like image 279
Zombies Avatar asked Feb 03 '10 21:02

Zombies


People also ask

Can you concatenate an empty string?

Concatenating with an Empty String VariableYou can use the concat() method with an empty string variable to concatenate primitive string values. By declaring a variable called totn_string as an empty string or '', you can invoke the String concat() method to concatenate primitive string values together.

How do I concatenate an empty string in Java?

To concatenate null to a string, use the + operator.

What is the correct way to concatenate the strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.


1 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'}"
like image 75
Peter Avatar answered Oct 31 '22 16:10

Peter