Is there a way in Ruby to make just any one out of many keyword arguments required? [closed] Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?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

Table formatting with tabularx?

Why not use the yoke to control yaw, as well as pitch and roll?

Pointing to problems without suggesting solutions

How can I list files in reverse time order by a command and pass them as arguments to another command?

Fit odd number of triplets in a measure?

French equivalents of おしゃれは足元から (Every good outfit starts with the shoes)

Why complex landing gears are used instead of simple, reliable and light weight muscle wire or shape memory alloys?

Plotting a Maclaurin series

Was the pager message from Nick Fury to Captain Marvel unnecessary?

Any stored/leased 737s that could substitute for grounded MAXs?

Found this skink in my tomato plant bucket. Is he trapped? Or could he leave if he wanted?

Marquee sign letters

Does the main washing effect of soap come from foam?

Is the time—manner—place ordering of adverbials an oversimplification?

How can I prevent/balance waiting and turtling as a response to cooldown mechanics

"Destructive power" carried by a B-52?

Does a random sequence of vectors span a Hilbert space?

How do I find my Spellcasting Ability for my D&D character?

Is there a spell that can create a permanent fire?

Is this Kuo-toa homebrew race balanced?

First paper to introduce the "principal-agent problem"

Besides transaction validation, are there any other uses of the Script language in Bitcoin

Why can't fire hurt Daenerys but it did to Jon Snow in season 1?

What are some likely causes to domain member PC losing contact to domain controller?



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



Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?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









$endgroup$



migration rejected from stackoverflow.com Apr 16 at 15:54


This question came from our site for professional and enthusiast programmers. Votes, comments, and answers are locked due to the question being closed here, but it may be eligible for editing and reopening on the site where it originated.





closed as off-topic by 200_success, Graipher, Vogel612 Apr 16 at 15:54


This question appears to be off-topic. The users who voted to close gave this specific reason:


  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – 200_success, Graipher, Vogel612
If this question can be reworded to fit the rules in the help center, please edit the question.






















    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









    $endgroup$



    migration rejected from stackoverflow.com Apr 16 at 15:54


    This question came from our site for professional and enthusiast programmers. Votes, comments, and answers are locked due to the question being closed here, but it may be eligible for editing and reopening on the site where it originated.





    closed as off-topic by 200_success, Graipher, Vogel612 Apr 16 at 15:54


    This question appears to be off-topic. The users who voted to close gave this specific reason:


    • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – 200_success, Graipher, Vogel612
    If this question can be reworded to fit the rules in the help center, please edit the question.


















      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









      $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












      share










      share



      share










      asked Apr 15 at 16:54









      ciejjciejj

      214




      214




      migration rejected from stackoverflow.com Apr 16 at 15:54


      This question came from our site for professional and enthusiast programmers. Votes, comments, and answers are locked due to the question being closed here, but it may be eligible for editing and reopening on the site where it originated.





      closed as off-topic by 200_success, Graipher, Vogel612 Apr 16 at 15:54


      This question appears to be off-topic. The users who voted to close gave this specific reason:


      • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – 200_success, Graipher, Vogel612
      If this question can be reworded to fit the rules in the help center, please edit the question.







      migration rejected from stackoverflow.com Apr 16 at 15:54


      This question came from our site for professional and enthusiast programmers. Votes, comments, and answers are locked due to the question being closed here, but it may be eligible for editing and reopening on the site where it originated.





      closed as off-topic by 200_success, Graipher, Vogel612 Apr 16 at 15:54


      This question appears to be off-topic. The users who voted to close gave this specific reason:


      • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – 200_success, Graipher, Vogel612
      If this question can be reworded to fit the rules in the help center, please edit the question.




















          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











          $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
            Apr 15 at 17:30



















          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








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











            $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
              Apr 15 at 17:30
















            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











            $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
              Apr 15 at 17:30














            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











            $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













            share


            share








            edited Apr 15 at 17:22

























            answered Apr 15 at 17:16









            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
              Apr 15 at 17:30

















            • $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
              Apr 15 at 17:30
















            $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
            Apr 15 at 17:30





            $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
            Apr 15 at 17:30














            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








            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








              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








                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








                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


                share






                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 Apr 15 at 17:21









                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.













                    Popular posts from this blog

                    Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

                    Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

                    Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020