Note that there are some explanatory texts on larger screens.

plurals
  1. PONamed arguments as local variables in Ruby
    primarykey
    data
    text
    <p>I find myself constantly writing what I see as unnecessary code in Ruby when using named arguments for methods.</p> <p>Take for example the following code:</p> <pre><code>def my_method(args) orange = args[:orange] lemon = args[:lemon] grapefruit = args[:grapefruit] # code that uses # orange, lemon &amp; grapefruit in this format which is way prettier &amp; concise than # args[:orange] args[:lemon] args[:grapefruit] puts "my_method variables: #{orange}, #{lemon}, #{grapefruit}" end my_method :orange =&gt; "Orange", :grapefruit =&gt; "Grapefruit" </code></pre> <p>What I really don't like about this code is that I am having to take the args and pass the values into local variables going against DRY principles and just generally taking up space in my methods. And if I don't use local variables and just refer to all variables with the args[:symbol] syntax then the code becomes somewhat illegible.</p> <p>I have tried working up a solution to this but keeping hitting a brick wall as I don't know how to define local variables using eval in the scope of the method, or using any other technique. Here is one of many attempts below, which results in an error</p> <pre><code>def my_method_with_eval(args) method_binding = binding %w{ orange lemon grapefruit}.each { |variable| eval "#{variable} = args[:#{variable}]", method_binding; } # code that uses # orange, lemon &amp; grapefruit in this format which is way prettier &amp; concise than # args[:orange] args[:lemon] args[:grapefruit] puts "my_method_with_eval variables: #{orange}, #{lemon}, #{grapefruit}" end my_method_with_eval :orange =&gt; "Orange", :grapefruit =&gt; "Grapefruit" </code></pre> <p>When running that code I simply get</p> <p><code>NameError: undefined local variable or method ‘orange’ for main:Object method my_method_with_eval in named_args_to_local_vars at line at top level in named_args_to_local_vars at line 9</code></p> <p>Anyone got any ideas how I could simplify this down somehow so that I don't have to start my named argument methods with loads of var=args[:var] code?</p> <p>Thanks, <a href="http://mattheworiordan.com/" rel="noreferrer">Matthew O'Riordan</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload