Checking for nil string before concatenating
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
ruby code-formatting
add a comment |
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
ruby code-formatting
add a comment |
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
ruby code-formatting
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
ruby code-formatting
ruby code-formatting
edited Jan 14 '15 at 2:44
JakeGould
20.6k84674
20.6k84674
asked Feb 3 '10 at 21:08
ZombiesZombies
10.6k32121202
10.6k32121202
add a comment |
add a comment |
6 Answers
6
active
oldest
votes
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'}"
7
if var1 isfalse
, you'll see 'unknown' instead.
– glenn jackman
Feb 4 '10 at 14:15
add a comment |
Use join
to add the strings which may be nil
.
The join
will not complain if there is a nil
For example:
["a","b",nil,"c"].join("")
#=> abc
However, if you are joining with anything but a blank string, like an underscore, you will get a join String for the nil
value:
["a","b",nil,"c"].join("_")
#=> a_b__c
To fix this, use .compact
to remove the nil
values from the Array
before joining:
["a","b",nil,"c"].compact.join("_")
#=> a_b_c
This is true only when joining by an empty ["a","b",nil,"c"].join("_") => "a_b__c" (notice the double underscore after 'b')
– pseudo
Aug 17 '17 at 11:14
2
@pseudo["a","b",nil,"c"].compact.join("_")
solves the problem
– Viktor
Sep 16 '17 at 15:37
@Viktor Thanks. Updated the answer to reflect this.
– Joshua Pinter
Nov 13 '18 at 18:08
add a comment |
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
add a comment |
Using ruby 2.4.1, to_s
resolves for both nil
and "Hello"
. So var1.to_s
should suffice.
2.4.1 :058 > nil.to_s
=> ""
2.4.1 :059 > "hello".to_s
=> "hello"
add a comment |
file.puts( "cn:" + (var1 || "UNKNOWN" ))
add a comment |
Since the "cn: "
part is purely aesthetical and therefore (more?) subject to change to meet future presentation guidelines, I would recommend using join;
file.puts(["cn", (var1 || "UNKNOWN")].join(": ")
Perhaps as a function, as mentioned earlier - semantics are the same, only method names/keywords have changed;
def value_or_unknown(value, attribute = nil)
[attribute, (value or "UNKNOWN")] * ": "
end
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2195453%2fchecking-for-nil-string-before-concatenating%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
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'}"
7
if var1 isfalse
, you'll see 'unknown' instead.
– glenn jackman
Feb 4 '10 at 14:15
add a comment |
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'}"
7
if var1 isfalse
, you'll see 'unknown' instead.
– glenn jackman
Feb 4 '10 at 14:15
add a comment |
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'}"
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'}"
edited Feb 3 '10 at 21:37
answered Feb 3 '10 at 21:12
PeterPeter
82.2k41157196
82.2k41157196
7
if var1 isfalse
, you'll see 'unknown' instead.
– glenn jackman
Feb 4 '10 at 14:15
add a comment |
7
if var1 isfalse
, you'll see 'unknown' instead.
– glenn jackman
Feb 4 '10 at 14:15
7
7
if var1 is
false
, you'll see 'unknown' instead.– glenn jackman
Feb 4 '10 at 14:15
if var1 is
false
, you'll see 'unknown' instead.– glenn jackman
Feb 4 '10 at 14:15
add a comment |
Use join
to add the strings which may be nil
.
The join
will not complain if there is a nil
For example:
["a","b",nil,"c"].join("")
#=> abc
However, if you are joining with anything but a blank string, like an underscore, you will get a join String for the nil
value:
["a","b",nil,"c"].join("_")
#=> a_b__c
To fix this, use .compact
to remove the nil
values from the Array
before joining:
["a","b",nil,"c"].compact.join("_")
#=> a_b_c
This is true only when joining by an empty ["a","b",nil,"c"].join("_") => "a_b__c" (notice the double underscore after 'b')
– pseudo
Aug 17 '17 at 11:14
2
@pseudo["a","b",nil,"c"].compact.join("_")
solves the problem
– Viktor
Sep 16 '17 at 15:37
@Viktor Thanks. Updated the answer to reflect this.
– Joshua Pinter
Nov 13 '18 at 18:08
add a comment |
Use join
to add the strings which may be nil
.
The join
will not complain if there is a nil
For example:
["a","b",nil,"c"].join("")
#=> abc
However, if you are joining with anything but a blank string, like an underscore, you will get a join String for the nil
value:
["a","b",nil,"c"].join("_")
#=> a_b__c
To fix this, use .compact
to remove the nil
values from the Array
before joining:
["a","b",nil,"c"].compact.join("_")
#=> a_b_c
This is true only when joining by an empty ["a","b",nil,"c"].join("_") => "a_b__c" (notice the double underscore after 'b')
– pseudo
Aug 17 '17 at 11:14
2
@pseudo["a","b",nil,"c"].compact.join("_")
solves the problem
– Viktor
Sep 16 '17 at 15:37
@Viktor Thanks. Updated the answer to reflect this.
– Joshua Pinter
Nov 13 '18 at 18:08
add a comment |
Use join
to add the strings which may be nil
.
The join
will not complain if there is a nil
For example:
["a","b",nil,"c"].join("")
#=> abc
However, if you are joining with anything but a blank string, like an underscore, you will get a join String for the nil
value:
["a","b",nil,"c"].join("_")
#=> a_b__c
To fix this, use .compact
to remove the nil
values from the Array
before joining:
["a","b",nil,"c"].compact.join("_")
#=> a_b_c
Use join
to add the strings which may be nil
.
The join
will not complain if there is a nil
For example:
["a","b",nil,"c"].join("")
#=> abc
However, if you are joining with anything but a blank string, like an underscore, you will get a join String for the nil
value:
["a","b",nil,"c"].join("_")
#=> a_b__c
To fix this, use .compact
to remove the nil
values from the Array
before joining:
["a","b",nil,"c"].compact.join("_")
#=> a_b_c
edited Nov 13 '18 at 18:08
Joshua Pinter
24.3k8138166
24.3k8138166
answered Jan 7 '15 at 3:21
user566245user566245
2,1872132
2,1872132
This is true only when joining by an empty ["a","b",nil,"c"].join("_") => "a_b__c" (notice the double underscore after 'b')
– pseudo
Aug 17 '17 at 11:14
2
@pseudo["a","b",nil,"c"].compact.join("_")
solves the problem
– Viktor
Sep 16 '17 at 15:37
@Viktor Thanks. Updated the answer to reflect this.
– Joshua Pinter
Nov 13 '18 at 18:08
add a comment |
This is true only when joining by an empty ["a","b",nil,"c"].join("_") => "a_b__c" (notice the double underscore after 'b')
– pseudo
Aug 17 '17 at 11:14
2
@pseudo["a","b",nil,"c"].compact.join("_")
solves the problem
– Viktor
Sep 16 '17 at 15:37
@Viktor Thanks. Updated the answer to reflect this.
– Joshua Pinter
Nov 13 '18 at 18:08
This is true only when joining by an empty ["a","b",nil,"c"].join("_") => "a_b__c" (notice the double underscore after 'b')
– pseudo
Aug 17 '17 at 11:14
This is true only when joining by an empty ["a","b",nil,"c"].join("_") => "a_b__c" (notice the double underscore after 'b')
– pseudo
Aug 17 '17 at 11:14
2
2
@pseudo
["a","b",nil,"c"].compact.join("_")
solves the problem– Viktor
Sep 16 '17 at 15:37
@pseudo
["a","b",nil,"c"].compact.join("_")
solves the problem– Viktor
Sep 16 '17 at 15:37
@Viktor Thanks. Updated the answer to reflect this.
– Joshua Pinter
Nov 13 '18 at 18:08
@Viktor Thanks. Updated the answer to reflect this.
– Joshua Pinter
Nov 13 '18 at 18:08
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Feb 3 '10 at 21:26
Brad G.Brad G.
716412
716412
add a comment |
add a comment |
Using ruby 2.4.1, to_s
resolves for both nil
and "Hello"
. So var1.to_s
should suffice.
2.4.1 :058 > nil.to_s
=> ""
2.4.1 :059 > "hello".to_s
=> "hello"
add a comment |
Using ruby 2.4.1, to_s
resolves for both nil
and "Hello"
. So var1.to_s
should suffice.
2.4.1 :058 > nil.to_s
=> ""
2.4.1 :059 > "hello".to_s
=> "hello"
add a comment |
Using ruby 2.4.1, to_s
resolves for both nil
and "Hello"
. So var1.to_s
should suffice.
2.4.1 :058 > nil.to_s
=> ""
2.4.1 :059 > "hello".to_s
=> "hello"
Using ruby 2.4.1, to_s
resolves for both nil
and "Hello"
. So var1.to_s
should suffice.
2.4.1 :058 > nil.to_s
=> ""
2.4.1 :059 > "hello".to_s
=> "hello"
answered Nov 29 '17 at 23:31
Julien LamarcheJulien Lamarche
3351315
3351315
add a comment |
add a comment |
file.puts( "cn:" + (var1 || "UNKNOWN" ))
add a comment |
file.puts( "cn:" + (var1 || "UNKNOWN" ))
add a comment |
file.puts( "cn:" + (var1 || "UNKNOWN" ))
file.puts( "cn:" + (var1 || "UNKNOWN" ))
answered Feb 3 '10 at 21:13
FarrelFarrel
2,2751714
2,2751714
add a comment |
add a comment |
Since the "cn: "
part is purely aesthetical and therefore (more?) subject to change to meet future presentation guidelines, I would recommend using join;
file.puts(["cn", (var1 || "UNKNOWN")].join(": ")
Perhaps as a function, as mentioned earlier - semantics are the same, only method names/keywords have changed;
def value_or_unknown(value, attribute = nil)
[attribute, (value or "UNKNOWN")] * ": "
end
add a comment |
Since the "cn: "
part is purely aesthetical and therefore (more?) subject to change to meet future presentation guidelines, I would recommend using join;
file.puts(["cn", (var1 || "UNKNOWN")].join(": ")
Perhaps as a function, as mentioned earlier - semantics are the same, only method names/keywords have changed;
def value_or_unknown(value, attribute = nil)
[attribute, (value or "UNKNOWN")] * ": "
end
add a comment |
Since the "cn: "
part is purely aesthetical and therefore (more?) subject to change to meet future presentation guidelines, I would recommend using join;
file.puts(["cn", (var1 || "UNKNOWN")].join(": ")
Perhaps as a function, as mentioned earlier - semantics are the same, only method names/keywords have changed;
def value_or_unknown(value, attribute = nil)
[attribute, (value or "UNKNOWN")] * ": "
end
Since the "cn: "
part is purely aesthetical and therefore (more?) subject to change to meet future presentation guidelines, I would recommend using join;
file.puts(["cn", (var1 || "UNKNOWN")].join(": ")
Perhaps as a function, as mentioned earlier - semantics are the same, only method names/keywords have changed;
def value_or_unknown(value, attribute = nil)
[attribute, (value or "UNKNOWN")] * ": "
end
edited Feb 21 '12 at 21:50
Jonas Heidelberg
3,90912036
3,90912036
answered Jun 20 '10 at 1:17
ZachZach
111
111
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2195453%2fchecking-for-nil-string-before-concatenating%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown