Why do Ruby's default parameter values not get assigned to nil arguments?











up vote
21
down vote

favorite
2












I'm new to Ruby and came across something that confused me a bit.



I set a default parameter value in a method signature.



When calling the method, I passed a nil argument to that parameter.



But the default value wasn't assigned; it remained nil.



# method with a default value of 1000 for parameter 'b'
def format_args(a, b=1000)
"t #{a.ljust(30,'.')} #{b}"
end

# test hash
dudes = {};
dudes["larry"] = 60
dudes["moe"] = nil

# expecting default parameter value
puts "Without nil check:"
dudes.each do |k,v|
puts format_args(k,v)
end

# forcing default parameter value
puts "With nil check:"
dudes.each do |k,v|
if v
puts format_args(k,v)
else
puts format_args(k)
end
end


Output:



Without nil check:
larry......................... 60
moe...........................
With nil check:
larry......................... 60
moe........................... 1000


Is this expected behavior?



What ruby-foo am I missing?



Seems like nil isn't the same "no value" that I'm accustomed to thinking of null in other languages.










share|improve this question




















  • 3




    Which other language would use the default value if you give it null?! null is a proper value in any language I know that uses null, just as nil is a proper value in Ruby.
    – Niklas B.
    May 8 '12 at 20:38












  • Passing a value to the function, any value, even nil for no value, overrides the default. If you want the default, omit the argument.
    – Michael Berkowski
    May 8 '12 at 20:39












  • Yep, you're absolutely right. It's not that other languages treat it differently; it's that my mental models are screwed up and it's taking me a bit to get my head back into the code...
    – Patrick Smith
    May 8 '12 at 20:46








  • 2




    @MichaelBerkowski Yeah great, but if you do not have ruby 2, how would you "omit" only the second out of 3 parameters?
    – user1115652
    May 1 '14 at 22:16










  • @NiklasB. C# does it like you mention and it makes passing arguments much easier.
    – Chris
    Oct 23 '17 at 20:20

















up vote
21
down vote

favorite
2












I'm new to Ruby and came across something that confused me a bit.



I set a default parameter value in a method signature.



When calling the method, I passed a nil argument to that parameter.



But the default value wasn't assigned; it remained nil.



# method with a default value of 1000 for parameter 'b'
def format_args(a, b=1000)
"t #{a.ljust(30,'.')} #{b}"
end

# test hash
dudes = {};
dudes["larry"] = 60
dudes["moe"] = nil

# expecting default parameter value
puts "Without nil check:"
dudes.each do |k,v|
puts format_args(k,v)
end

# forcing default parameter value
puts "With nil check:"
dudes.each do |k,v|
if v
puts format_args(k,v)
else
puts format_args(k)
end
end


Output:



Without nil check:
larry......................... 60
moe...........................
With nil check:
larry......................... 60
moe........................... 1000


Is this expected behavior?



What ruby-foo am I missing?



Seems like nil isn't the same "no value" that I'm accustomed to thinking of null in other languages.










share|improve this question




















  • 3




    Which other language would use the default value if you give it null?! null is a proper value in any language I know that uses null, just as nil is a proper value in Ruby.
    – Niklas B.
    May 8 '12 at 20:38












  • Passing a value to the function, any value, even nil for no value, overrides the default. If you want the default, omit the argument.
    – Michael Berkowski
    May 8 '12 at 20:39












  • Yep, you're absolutely right. It's not that other languages treat it differently; it's that my mental models are screwed up and it's taking me a bit to get my head back into the code...
    – Patrick Smith
    May 8 '12 at 20:46








  • 2




    @MichaelBerkowski Yeah great, but if you do not have ruby 2, how would you "omit" only the second out of 3 parameters?
    – user1115652
    May 1 '14 at 22:16










  • @NiklasB. C# does it like you mention and it makes passing arguments much easier.
    – Chris
    Oct 23 '17 at 20:20















up vote
21
down vote

favorite
2









up vote
21
down vote

favorite
2






2





I'm new to Ruby and came across something that confused me a bit.



I set a default parameter value in a method signature.



When calling the method, I passed a nil argument to that parameter.



But the default value wasn't assigned; it remained nil.



# method with a default value of 1000 for parameter 'b'
def format_args(a, b=1000)
"t #{a.ljust(30,'.')} #{b}"
end

# test hash
dudes = {};
dudes["larry"] = 60
dudes["moe"] = nil

# expecting default parameter value
puts "Without nil check:"
dudes.each do |k,v|
puts format_args(k,v)
end

# forcing default parameter value
puts "With nil check:"
dudes.each do |k,v|
if v
puts format_args(k,v)
else
puts format_args(k)
end
end


Output:



Without nil check:
larry......................... 60
moe...........................
With nil check:
larry......................... 60
moe........................... 1000


Is this expected behavior?



What ruby-foo am I missing?



Seems like nil isn't the same "no value" that I'm accustomed to thinking of null in other languages.










share|improve this question















I'm new to Ruby and came across something that confused me a bit.



I set a default parameter value in a method signature.



When calling the method, I passed a nil argument to that parameter.



But the default value wasn't assigned; it remained nil.



# method with a default value of 1000 for parameter 'b'
def format_args(a, b=1000)
"t #{a.ljust(30,'.')} #{b}"
end

# test hash
dudes = {};
dudes["larry"] = 60
dudes["moe"] = nil

# expecting default parameter value
puts "Without nil check:"
dudes.each do |k,v|
puts format_args(k,v)
end

# forcing default parameter value
puts "With nil check:"
dudes.each do |k,v|
if v
puts format_args(k,v)
else
puts format_args(k)
end
end


Output:



Without nil check:
larry......................... 60
moe...........................
With nil check:
larry......................... 60
moe........................... 1000


Is this expected behavior?



What ruby-foo am I missing?



Seems like nil isn't the same "no value" that I'm accustomed to thinking of null in other languages.







ruby






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 8 '12 at 20:43

























asked May 8 '12 at 20:35









Patrick Smith

5471511




5471511








  • 3




    Which other language would use the default value if you give it null?! null is a proper value in any language I know that uses null, just as nil is a proper value in Ruby.
    – Niklas B.
    May 8 '12 at 20:38












  • Passing a value to the function, any value, even nil for no value, overrides the default. If you want the default, omit the argument.
    – Michael Berkowski
    May 8 '12 at 20:39












  • Yep, you're absolutely right. It's not that other languages treat it differently; it's that my mental models are screwed up and it's taking me a bit to get my head back into the code...
    – Patrick Smith
    May 8 '12 at 20:46








  • 2




    @MichaelBerkowski Yeah great, but if you do not have ruby 2, how would you "omit" only the second out of 3 parameters?
    – user1115652
    May 1 '14 at 22:16










  • @NiklasB. C# does it like you mention and it makes passing arguments much easier.
    – Chris
    Oct 23 '17 at 20:20
















  • 3




    Which other language would use the default value if you give it null?! null is a proper value in any language I know that uses null, just as nil is a proper value in Ruby.
    – Niklas B.
    May 8 '12 at 20:38












  • Passing a value to the function, any value, even nil for no value, overrides the default. If you want the default, omit the argument.
    – Michael Berkowski
    May 8 '12 at 20:39












  • Yep, you're absolutely right. It's not that other languages treat it differently; it's that my mental models are screwed up and it's taking me a bit to get my head back into the code...
    – Patrick Smith
    May 8 '12 at 20:46








  • 2




    @MichaelBerkowski Yeah great, but if you do not have ruby 2, how would you "omit" only the second out of 3 parameters?
    – user1115652
    May 1 '14 at 22:16










  • @NiklasB. C# does it like you mention and it makes passing arguments much easier.
    – Chris
    Oct 23 '17 at 20:20










3




3




Which other language would use the default value if you give it null?! null is a proper value in any language I know that uses null, just as nil is a proper value in Ruby.
– Niklas B.
May 8 '12 at 20:38






Which other language would use the default value if you give it null?! null is a proper value in any language I know that uses null, just as nil is a proper value in Ruby.
– Niklas B.
May 8 '12 at 20:38














Passing a value to the function, any value, even nil for no value, overrides the default. If you want the default, omit the argument.
– Michael Berkowski
May 8 '12 at 20:39






Passing a value to the function, any value, even nil for no value, overrides the default. If you want the default, omit the argument.
– Michael Berkowski
May 8 '12 at 20:39














Yep, you're absolutely right. It's not that other languages treat it differently; it's that my mental models are screwed up and it's taking me a bit to get my head back into the code...
– Patrick Smith
May 8 '12 at 20:46






Yep, you're absolutely right. It's not that other languages treat it differently; it's that my mental models are screwed up and it's taking me a bit to get my head back into the code...
– Patrick Smith
May 8 '12 at 20:46






2




2




@MichaelBerkowski Yeah great, but if you do not have ruby 2, how would you "omit" only the second out of 3 parameters?
– user1115652
May 1 '14 at 22:16




@MichaelBerkowski Yeah great, but if you do not have ruby 2, how would you "omit" only the second out of 3 parameters?
– user1115652
May 1 '14 at 22:16












@NiklasB. C# does it like you mention and it makes passing arguments much easier.
– Chris
Oct 23 '17 at 20:20






@NiklasB. C# does it like you mention and it makes passing arguments much easier.
– Chris
Oct 23 '17 at 20:20














4 Answers
4






active

oldest

votes

















up vote
47
down vote



accepted










The default parameter is used when the parameter isn't provided.



If you provide it as nil, then it will be nil. So yes, this is expected behavior.






share|improve this answer




























    up vote
    31
    down vote













    If you want to set a default value, even if nil is passed, and still allow calling the method without an argument you need to set the default value to nil and use the "or equals" operator:



    def foo(bar=nil)
    bar ||= "default value"
    puts bar
    end





    share|improve this answer




























      up vote
      0
      down vote













      In Ruby, methods always return something. Sometimes, there is nothing to return (query in database turns up empty or something like that). nil is for those cases; It means something like 'nothing here', but it is a reference to an object. To get the behaviour you want, just pass no parameter.



      def talk(msg="Hello")
      puts msg
      end

      talk #=> "Hello"





      share|improve this answer

















      • 4




        Or use nil as the default argument and do a msg ||= "Hello" inside the function.
        – Niklas B.
        May 8 '12 at 20:52


















      up vote
      0
      down vote













      Try ... v.is_nil? in the if statement.






      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%2f10506091%2fwhy-do-rubys-default-parameter-values-not-get-assigned-to-nil-arguments%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        47
        down vote



        accepted










        The default parameter is used when the parameter isn't provided.



        If you provide it as nil, then it will be nil. So yes, this is expected behavior.






        share|improve this answer

























          up vote
          47
          down vote



          accepted










          The default parameter is used when the parameter isn't provided.



          If you provide it as nil, then it will be nil. So yes, this is expected behavior.






          share|improve this answer























            up vote
            47
            down vote



            accepted







            up vote
            47
            down vote



            accepted






            The default parameter is used when the parameter isn't provided.



            If you provide it as nil, then it will be nil. So yes, this is expected behavior.






            share|improve this answer












            The default parameter is used when the parameter isn't provided.



            If you provide it as nil, then it will be nil. So yes, this is expected behavior.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered May 8 '12 at 20:39









            Jeremy

            19.2k45576




            19.2k45576
























                up vote
                31
                down vote













                If you want to set a default value, even if nil is passed, and still allow calling the method without an argument you need to set the default value to nil and use the "or equals" operator:



                def foo(bar=nil)
                bar ||= "default value"
                puts bar
                end





                share|improve this answer

























                  up vote
                  31
                  down vote













                  If you want to set a default value, even if nil is passed, and still allow calling the method without an argument you need to set the default value to nil and use the "or equals" operator:



                  def foo(bar=nil)
                  bar ||= "default value"
                  puts bar
                  end





                  share|improve this answer























                    up vote
                    31
                    down vote










                    up vote
                    31
                    down vote









                    If you want to set a default value, even if nil is passed, and still allow calling the method without an argument you need to set the default value to nil and use the "or equals" operator:



                    def foo(bar=nil)
                    bar ||= "default value"
                    puts bar
                    end





                    share|improve this answer












                    If you want to set a default value, even if nil is passed, and still allow calling the method without an argument you need to set the default value to nil and use the "or equals" operator:



                    def foo(bar=nil)
                    bar ||= "default value"
                    puts bar
                    end






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Apr 28 '14 at 14:30









                    Mike Bethany

                    1,2851312




                    1,2851312






















                        up vote
                        0
                        down vote













                        In Ruby, methods always return something. Sometimes, there is nothing to return (query in database turns up empty or something like that). nil is for those cases; It means something like 'nothing here', but it is a reference to an object. To get the behaviour you want, just pass no parameter.



                        def talk(msg="Hello")
                        puts msg
                        end

                        talk #=> "Hello"





                        share|improve this answer

















                        • 4




                          Or use nil as the default argument and do a msg ||= "Hello" inside the function.
                          – Niklas B.
                          May 8 '12 at 20:52















                        up vote
                        0
                        down vote













                        In Ruby, methods always return something. Sometimes, there is nothing to return (query in database turns up empty or something like that). nil is for those cases; It means something like 'nothing here', but it is a reference to an object. To get the behaviour you want, just pass no parameter.



                        def talk(msg="Hello")
                        puts msg
                        end

                        talk #=> "Hello"





                        share|improve this answer

















                        • 4




                          Or use nil as the default argument and do a msg ||= "Hello" inside the function.
                          – Niklas B.
                          May 8 '12 at 20:52













                        up vote
                        0
                        down vote










                        up vote
                        0
                        down vote









                        In Ruby, methods always return something. Sometimes, there is nothing to return (query in database turns up empty or something like that). nil is for those cases; It means something like 'nothing here', but it is a reference to an object. To get the behaviour you want, just pass no parameter.



                        def talk(msg="Hello")
                        puts msg
                        end

                        talk #=> "Hello"





                        share|improve this answer












                        In Ruby, methods always return something. Sometimes, there is nothing to return (query in database turns up empty or something like that). nil is for those cases; It means something like 'nothing here', but it is a reference to an object. To get the behaviour you want, just pass no parameter.



                        def talk(msg="Hello")
                        puts msg
                        end

                        talk #=> "Hello"






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered May 8 '12 at 20:49









                        steenslag

                        61.6k1199137




                        61.6k1199137








                        • 4




                          Or use nil as the default argument and do a msg ||= "Hello" inside the function.
                          – Niklas B.
                          May 8 '12 at 20:52














                        • 4




                          Or use nil as the default argument and do a msg ||= "Hello" inside the function.
                          – Niklas B.
                          May 8 '12 at 20:52








                        4




                        4




                        Or use nil as the default argument and do a msg ||= "Hello" inside the function.
                        – Niklas B.
                        May 8 '12 at 20:52




                        Or use nil as the default argument and do a msg ||= "Hello" inside the function.
                        – Niklas B.
                        May 8 '12 at 20:52










                        up vote
                        0
                        down vote













                        Try ... v.is_nil? in the if statement.






                        share|improve this answer

























                          up vote
                          0
                          down vote













                          Try ... v.is_nil? in the if statement.






                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            Try ... v.is_nil? in the if statement.






                            share|improve this answer












                            Try ... v.is_nil? in the if statement.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Sep 28 '13 at 11:20









                            King'ori Maina

                            3,15921630




                            3,15921630






























                                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.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • 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%2f10506091%2fwhy-do-rubys-default-parameter-values-not-get-assigned-to-nil-arguments%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

                                If I really need a card on my start hand, how many mulligans make sense? [duplicate]

                                Alcedinidae

                                Can an atomic nucleus contain both particles and antiparticles? [duplicate]