Is there a way in Ruby to make just any one out of many keyword arguments required? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Ruby on rails complex select statement…there has to be a better way!What if any design issues are there in this method of loading configuration data from YAML in Ruby?Is there a more succinct way to write this Ruby function?Are there any glaring issues with the way I write and test my Ruby classes?Pretty way of keeping sensitive info out of a logged command string in Ruby?Machi Koro card/dice game

When is phishing education going too far?

Is there a documented rationale why the House Ways and Means chairman can demand tax info?

Letter Boxed validator

Does surprise arrest existing movement?

Did Xerox really develop the first LAN?

How do I mention the quality of my school without bragging

Proof involving the spectral radius and Jordan Canonical form

Is there a Spanish version of "dot your i's and cross your t's" that includes the letter 'ñ'?

Models of set theory where not every set can be linearly ordered

Is there a "higher Segal conjecture"?

How to bypass password on Windows XP account?

Is the Standard Deduction better than Itemized when both are the same amount?

Single word antonym of "flightless"

How to find all the available tools in macOS terminal?

What's the purpose of writing one's academic bio in 3rd person?

What makes black pepper strong or mild?

Output the ŋarâþ crîþ alphabet song without using (m)any letters

Bonus calculation: Am I making a mountain out of a molehill?

How to motivate offshore teams and trust them to deliver?

Sorting numerically

How do I keep my slimes from escaping their pens?

Can inflation occur in a positive-sum game currency system such as the Stack Exchange reputation system?

Can a non-EU citizen traveling with me come with me through the EU passport line?

What does the "x" in "x86" represent?



Is there a way in Ruby to make just any one out of many keyword arguments required?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Ruby on rails complex select statement…there has to be a better way!What if any design issues are there in this method of loading configuration data from YAML in Ruby?Is there a more succinct way to write this Ruby function?Are there any glaring issues with the way I write and test my Ruby classes?Pretty way of keeping sensitive info out of a logged command string in Ruby?Machi Koro card/dice game



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2












$begingroup$


I am trying to write a method, that works with three types of arguments, but requires only one of them.



def convert(arg_a: 1, arg_b: 2, arg_c: 'foo')
end


Please note, that both: arg_a, and arg_b are the same type (let's say Numeric), so using one mandatory argument, and then making decision based on the input type won't work here.



At this point my code looks like this:



def convert(arg_a: nil, arg_b: nil, arg_c: nil)
if arg_b.nil? && arg_c.nil? && arg_a
# do something with arg_a
elsif arg_a.nil? && arg_c.nil? && arg_b
# do something with arg_b
elsif arg_a.nil? && arg_b.nil? && arg_c
# do something with arg_c
else
raise ArgumentError
end


In my opinion this code smells a little, and can be improved. Any thoughts?










share|improve this question









$endgroup$



migrated from stackoverflow.com 9 hours ago


This question came from our site for professional and enthusiast programmers.
























    2












    $begingroup$


    I am trying to write a method, that works with three types of arguments, but requires only one of them.



    def convert(arg_a: 1, arg_b: 2, arg_c: 'foo')
    end


    Please note, that both: arg_a, and arg_b are the same type (let's say Numeric), so using one mandatory argument, and then making decision based on the input type won't work here.



    At this point my code looks like this:



    def convert(arg_a: nil, arg_b: nil, arg_c: nil)
    if arg_b.nil? && arg_c.nil? && arg_a
    # do something with arg_a
    elsif arg_a.nil? && arg_c.nil? && arg_b
    # do something with arg_b
    elsif arg_a.nil? && arg_b.nil? && arg_c
    # do something with arg_c
    else
    raise ArgumentError
    end


    In my opinion this code smells a little, and can be improved. Any thoughts?










    share|improve this question









    $endgroup$



    migrated from stackoverflow.com 9 hours ago


    This question came from our site for professional and enthusiast programmers.




















      2












      2








      2





      $begingroup$


      I am trying to write a method, that works with three types of arguments, but requires only one of them.



      def convert(arg_a: 1, arg_b: 2, arg_c: 'foo')
      end


      Please note, that both: arg_a, and arg_b are the same type (let's say Numeric), so using one mandatory argument, and then making decision based on the input type won't work here.



      At this point my code looks like this:



      def convert(arg_a: nil, arg_b: nil, arg_c: nil)
      if arg_b.nil? && arg_c.nil? && arg_a
      # do something with arg_a
      elsif arg_a.nil? && arg_c.nil? && arg_b
      # do something with arg_b
      elsif arg_a.nil? && arg_b.nil? && arg_c
      # do something with arg_c
      else
      raise ArgumentError
      end


      In my opinion this code smells a little, and can be improved. Any thoughts?










      share|improve this question









      $endgroup$




      I am trying to write a method, that works with three types of arguments, but requires only one of them.



      def convert(arg_a: 1, arg_b: 2, arg_c: 'foo')
      end


      Please note, that both: arg_a, and arg_b are the same type (let's say Numeric), so using one mandatory argument, and then making decision based on the input type won't work here.



      At this point my code looks like this:



      def convert(arg_a: nil, arg_b: nil, arg_c: nil)
      if arg_b.nil? && arg_c.nil? && arg_a
      # do something with arg_a
      elsif arg_a.nil? && arg_c.nil? && arg_b
      # do something with arg_b
      elsif arg_a.nil? && arg_b.nil? && arg_c
      # do something with arg_c
      else
      raise ArgumentError
      end


      In my opinion this code smells a little, and can be improved. Any thoughts?







      ruby






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 10 hours ago









      ciejjciejj

      214




      214




      migrated from stackoverflow.com 9 hours ago


      This question came from our site for professional and enthusiast programmers.









      migrated from stackoverflow.com 9 hours ago


      This question came from our site for professional and enthusiast programmers.






















          2 Answers
          2






          active

          oldest

          votes


















          4












          $begingroup$

          There are lots of ways of improving this; at a high level, I'd say it's possible the method itself should be broken up into multiple methods with distinct names, because a method that accepts three different inputs and does three different things with them probably doesn't have a single responsibility.



          That not withstanding, you can clean this method up by separating the argument validation from the rest of the logic. There are lots of ways of doing this, but if you just need exactly one non-nil argument, you can use something along these lines:



          def convert(arg_a: nil, arg_b: nil, arg_c: nil)
          raise ArgumentError unless [arg_a, arg_b, arg_c].compact.one?

          if arg_a
          # do something with arg_a
          elsif arg_b
          # do something with arg_b
          elsif arg_c
          # do something with arg_c
          end
          end





          share|improve this answer











          $endgroup$












          • $begingroup$
            The solution proposed by you does makes the code much clearer - I think this is the answer I was looking for. This convert method is only for argument validation - based on it other methods are called.
            $endgroup$
            – ciejj
            9 hours ago



















          2












          $begingroup$

          From what I can tell, your implementation only makes use of one of the three arguments, and only really expects (or allows) a single argument at a time.



          i.e., with your current implementation, this is what an error-free call-site looks like:



          convert(arg_a: 1)
          convert(arg_b: 2)
          convert(arg_c: 'foo')


          If the method were called with two or more arguments (any of them), it would raise an ArgumentError, so really, this method can only be called with a single argument.



          Given that you're already using keyword arguments with a default value of nil, I cannot see how this is any better than simply writing three different methods that handle the three values. Therefore, something like...



          def convert_arg_a(a)
          # Handle a...
          end

          def convert_arg_b(b)
          # Handle b...
          end

          def convert_arg_c(c)
          # Handle c...
          end


          ...should be able to do exactly what is possible with the implementation you've described, with none of the branching.






          share|improve this answer








          New contributor




          Hari Gopal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          $endgroup$













            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: "196"
            ;
            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: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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%2fcodereview.stackexchange.com%2fquestions%2f217502%2fis-there-a-way-in-ruby-to-make-just-any-one-out-of-many-keyword-arguments-requir%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            4












            $begingroup$

            There are lots of ways of improving this; at a high level, I'd say it's possible the method itself should be broken up into multiple methods with distinct names, because a method that accepts three different inputs and does three different things with them probably doesn't have a single responsibility.



            That not withstanding, you can clean this method up by separating the argument validation from the rest of the logic. There are lots of ways of doing this, but if you just need exactly one non-nil argument, you can use something along these lines:



            def convert(arg_a: nil, arg_b: nil, arg_c: nil)
            raise ArgumentError unless [arg_a, arg_b, arg_c].compact.one?

            if arg_a
            # do something with arg_a
            elsif arg_b
            # do something with arg_b
            elsif arg_c
            # do something with arg_c
            end
            end





            share|improve this answer











            $endgroup$












            • $begingroup$
              The solution proposed by you does makes the code much clearer - I think this is the answer I was looking for. This convert method is only for argument validation - based on it other methods are called.
              $endgroup$
              – ciejj
              9 hours ago
















            4












            $begingroup$

            There are lots of ways of improving this; at a high level, I'd say it's possible the method itself should be broken up into multiple methods with distinct names, because a method that accepts three different inputs and does three different things with them probably doesn't have a single responsibility.



            That not withstanding, you can clean this method up by separating the argument validation from the rest of the logic. There are lots of ways of doing this, but if you just need exactly one non-nil argument, you can use something along these lines:



            def convert(arg_a: nil, arg_b: nil, arg_c: nil)
            raise ArgumentError unless [arg_a, arg_b, arg_c].compact.one?

            if arg_a
            # do something with arg_a
            elsif arg_b
            # do something with arg_b
            elsif arg_c
            # do something with arg_c
            end
            end





            share|improve this answer











            $endgroup$












            • $begingroup$
              The solution proposed by you does makes the code much clearer - I think this is the answer I was looking for. This convert method is only for argument validation - based on it other methods are called.
              $endgroup$
              – ciejj
              9 hours ago














            4












            4








            4





            $begingroup$

            There are lots of ways of improving this; at a high level, I'd say it's possible the method itself should be broken up into multiple methods with distinct names, because a method that accepts three different inputs and does three different things with them probably doesn't have a single responsibility.



            That not withstanding, you can clean this method up by separating the argument validation from the rest of the logic. There are lots of ways of doing this, but if you just need exactly one non-nil argument, you can use something along these lines:



            def convert(arg_a: nil, arg_b: nil, arg_c: nil)
            raise ArgumentError unless [arg_a, arg_b, arg_c].compact.one?

            if arg_a
            # do something with arg_a
            elsif arg_b
            # do something with arg_b
            elsif arg_c
            # do something with arg_c
            end
            end





            share|improve this answer











            $endgroup$



            There are lots of ways of improving this; at a high level, I'd say it's possible the method itself should be broken up into multiple methods with distinct names, because a method that accepts three different inputs and does three different things with them probably doesn't have a single responsibility.



            That not withstanding, you can clean this method up by separating the argument validation from the rest of the logic. There are lots of ways of doing this, but if you just need exactly one non-nil argument, you can use something along these lines:



            def convert(arg_a: nil, arg_b: nil, arg_c: nil)
            raise ArgumentError unless [arg_a, arg_b, arg_c].compact.one?

            if arg_a
            # do something with arg_a
            elsif arg_b
            # do something with arg_b
            elsif arg_c
            # do something with arg_c
            end
            end






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 9 hours ago

























            answered 9 hours ago









            meagarmeagar

            878513




            878513











            • $begingroup$
              The solution proposed by you does makes the code much clearer - I think this is the answer I was looking for. This convert method is only for argument validation - based on it other methods are called.
              $endgroup$
              – ciejj
              9 hours ago

















            • $begingroup$
              The solution proposed by you does makes the code much clearer - I think this is the answer I was looking for. This convert method is only for argument validation - based on it other methods are called.
              $endgroup$
              – ciejj
              9 hours ago
















            $begingroup$
            The solution proposed by you does makes the code much clearer - I think this is the answer I was looking for. This convert method is only for argument validation - based on it other methods are called.
            $endgroup$
            – ciejj
            9 hours ago





            $begingroup$
            The solution proposed by you does makes the code much clearer - I think this is the answer I was looking for. This convert method is only for argument validation - based on it other methods are called.
            $endgroup$
            – ciejj
            9 hours ago














            2












            $begingroup$

            From what I can tell, your implementation only makes use of one of the three arguments, and only really expects (or allows) a single argument at a time.



            i.e., with your current implementation, this is what an error-free call-site looks like:



            convert(arg_a: 1)
            convert(arg_b: 2)
            convert(arg_c: 'foo')


            If the method were called with two or more arguments (any of them), it would raise an ArgumentError, so really, this method can only be called with a single argument.



            Given that you're already using keyword arguments with a default value of nil, I cannot see how this is any better than simply writing three different methods that handle the three values. Therefore, something like...



            def convert_arg_a(a)
            # Handle a...
            end

            def convert_arg_b(b)
            # Handle b...
            end

            def convert_arg_c(c)
            # Handle c...
            end


            ...should be able to do exactly what is possible with the implementation you've described, with none of the branching.






            share|improve this answer








            New contributor




            Hari Gopal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






            $endgroup$

















              2












              $begingroup$

              From what I can tell, your implementation only makes use of one of the three arguments, and only really expects (or allows) a single argument at a time.



              i.e., with your current implementation, this is what an error-free call-site looks like:



              convert(arg_a: 1)
              convert(arg_b: 2)
              convert(arg_c: 'foo')


              If the method were called with two or more arguments (any of them), it would raise an ArgumentError, so really, this method can only be called with a single argument.



              Given that you're already using keyword arguments with a default value of nil, I cannot see how this is any better than simply writing three different methods that handle the three values. Therefore, something like...



              def convert_arg_a(a)
              # Handle a...
              end

              def convert_arg_b(b)
              # Handle b...
              end

              def convert_arg_c(c)
              # Handle c...
              end


              ...should be able to do exactly what is possible with the implementation you've described, with none of the branching.






              share|improve this answer








              New contributor




              Hari Gopal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.






              $endgroup$















                2












                2








                2





                $begingroup$

                From what I can tell, your implementation only makes use of one of the three arguments, and only really expects (or allows) a single argument at a time.



                i.e., with your current implementation, this is what an error-free call-site looks like:



                convert(arg_a: 1)
                convert(arg_b: 2)
                convert(arg_c: 'foo')


                If the method were called with two or more arguments (any of them), it would raise an ArgumentError, so really, this method can only be called with a single argument.



                Given that you're already using keyword arguments with a default value of nil, I cannot see how this is any better than simply writing three different methods that handle the three values. Therefore, something like...



                def convert_arg_a(a)
                # Handle a...
                end

                def convert_arg_b(b)
                # Handle b...
                end

                def convert_arg_c(c)
                # Handle c...
                end


                ...should be able to do exactly what is possible with the implementation you've described, with none of the branching.






                share|improve this answer








                New contributor




                Hari Gopal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                $endgroup$



                From what I can tell, your implementation only makes use of one of the three arguments, and only really expects (or allows) a single argument at a time.



                i.e., with your current implementation, this is what an error-free call-site looks like:



                convert(arg_a: 1)
                convert(arg_b: 2)
                convert(arg_c: 'foo')


                If the method were called with two or more arguments (any of them), it would raise an ArgumentError, so really, this method can only be called with a single argument.



                Given that you're already using keyword arguments with a default value of nil, I cannot see how this is any better than simply writing three different methods that handle the three values. Therefore, something like...



                def convert_arg_a(a)
                # Handle a...
                end

                def convert_arg_b(b)
                # Handle b...
                end

                def convert_arg_c(c)
                # Handle c...
                end


                ...should be able to do exactly what is possible with the implementation you've described, with none of the branching.







                share|improve this answer








                New contributor




                Hari Gopal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                share|improve this answer



                share|improve this answer






                New contributor




                Hari Gopal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                answered 9 hours ago









                Hari GopalHari Gopal

                1211




                1211




                New contributor




                Hari Gopal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.





                New contributor





                Hari Gopal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                Hari Gopal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • 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.

                    Use MathJax to format equations. MathJax reference.


                    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%2fcodereview.stackexchange.com%2fquestions%2f217502%2fis-there-a-way-in-ruby-to-make-just-any-one-out-of-many-keyword-arguments-requir%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

                    How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

                    Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

                    Чепеларе Съдържание География | История | Население | Спортни и природни забележителности | Културни и исторически обекти | Религии | Обществени институции | Известни личности | Редовни събития | Галерия | Източници | Литература | Външни препратки | Навигация41°43′23.99″ с. ш. 24°41′09.99″ и. д. / 41.723333° с. ш. 24.686111° и. д.*ЧепелареЧепеларски Linux fest 2002Начало на Зимен сезон 2005/06Национални хайдушки празници „Капитан Петко Войвода“Град ЧепелареЧепеларе – народният ски курортbgrod.orgwww.terranatura.hit.bgСправка за населението на гр. Исперих, общ. Исперих, обл. РазградМузей на родопския карстМузей на спорта и скитеЧепеларебългарскибългарскианглийскитукИстория на градаСки писти в ЧепелареВремето в ЧепелареРадио и телевизия в ЧепелареЧепеларе мами с родопски чар и добри пистиЕвтин туризъм и снежни атракции в ЧепелареМестоположениеИнформация и снимки от музея на родопския карст3D панорами от ЧепелареЧепелареррр