Checking for nil string before concatenating












16















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










share|improve this question





























    16















    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










    share|improve this question



























      16












      16








      16


      3






      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










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 14 '15 at 2:44









      JakeGould

      20.6k84674




      20.6k84674










      asked Feb 3 '10 at 21:08









      ZombiesZombies

      10.6k32121202




      10.6k32121202
























          6 Answers
          6






          active

          oldest

          votes


















          42














          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'}"





          share|improve this answer





















          • 7





            if var1 is false, you'll see 'unknown' instead.

            – glenn jackman
            Feb 4 '10 at 14:15



















          8














          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





          share|improve this answer


























          • 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



















          4














          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






          share|improve this answer































            2














            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"





            share|improve this answer































              1














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





              share|improve this answer































                1














                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





                share|improve this answer

























                  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
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  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









                  42














                  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'}"





                  share|improve this answer





















                  • 7





                    if var1 is false, you'll see 'unknown' instead.

                    – glenn jackman
                    Feb 4 '10 at 14:15
















                  42














                  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'}"





                  share|improve this answer





















                  • 7





                    if var1 is false, you'll see 'unknown' instead.

                    – glenn jackman
                    Feb 4 '10 at 14:15














                  42












                  42








                  42







                  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'}"





                  share|improve this answer















                  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'}"






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Feb 3 '10 at 21:37

























                  answered Feb 3 '10 at 21:12









                  PeterPeter

                  82.2k41157196




                  82.2k41157196








                  • 7





                    if var1 is false, you'll see 'unknown' instead.

                    – glenn jackman
                    Feb 4 '10 at 14:15














                  • 7





                    if var1 is false, 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













                  8














                  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





                  share|improve this answer


























                  • 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
















                  8














                  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





                  share|improve this answer


























                  • 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














                  8












                  8








                  8







                  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





                  share|improve this answer















                  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






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  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



















                  • 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











                  4














                  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






                  share|improve this answer




























                    4














                    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






                    share|improve this answer


























                      4












                      4








                      4







                      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






                      share|improve this answer













                      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







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Feb 3 '10 at 21:26









                      Brad G.Brad G.

                      716412




                      716412























                          2














                          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"





                          share|improve this answer




























                            2














                            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"





                            share|improve this answer


























                              2












                              2








                              2







                              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"





                              share|improve this answer













                              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"






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 29 '17 at 23:31









                              Julien LamarcheJulien Lamarche

                              3351315




                              3351315























                                  1














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





                                  share|improve this answer




























                                    1














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





                                    share|improve this answer


























                                      1












                                      1








                                      1







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





                                      share|improve this answer













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






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Feb 3 '10 at 21:13









                                      FarrelFarrel

                                      2,2751714




                                      2,2751714























                                          1














                                          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





                                          share|improve this answer






























                                            1














                                            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





                                            share|improve this answer




























                                              1












                                              1








                                              1







                                              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





                                              share|improve this answer















                                              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






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Feb 21 '12 at 21:50









                                              Jonas Heidelberg

                                              3,90912036




                                              3,90912036










                                              answered Jun 20 '10 at 1:17









                                              ZachZach

                                              111




                                              111






























                                                  draft saved

                                                  draft discarded




















































                                                  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.




                                                  draft saved


                                                  draft discarded














                                                  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





















































                                                  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







                                                  Popular posts from this blog

                                                  Florida Star v. B. J. F.

                                                  Error while running script in elastic search , gateway timeout

                                                  Adding quotations to stringified JSON object values