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
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.
To concatenate null to a string, use the + operator.
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.
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'}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With