Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>At my blog (see link in user info), I just tried to address handling this problem neatly. I go into more detail there, but the core of my solution is the following helper method:</p> <pre><code>def collect_named_args(given, expected) # collect any given arguments that were unexpected bad = given.keys - expected.keys # if we have any unexpected arguments, raise an exception. # Example error string: "unknown arguments sonething, anyhting" raise ArgumentError, "unknown argument#{bad.count &gt; 1 ? 's' : ''}: #{bad.join(', ')}", caller unless bad.empty? Struct.new(*expected.keys).new( *expected.map { |arg, default_value| given.has_key?(arg) ? given[arg] : default_value } ) end # def collect_named_args </code></pre> <p>which is called as follows:</p> <pre><code>def foo(arguments = {}) a = collect_named_args(arguments, something: 'nothing', everything: 'almost', nothing: false, anything: 75) # Do something with the arguments puts a.anything end # def foo </code></pre> <p>I'm still trying to figure out if there is any way to get my results into local_variables or not - but as others have noted, Ruby doesn't want to do that. You could use the "with" trick, I suppose.</p> <pre><code>module Kernel def with(object, &amp;block) object.instance_eval &amp;block end end </code></pre> <p>then</p> <pre><code>with(a) do # Do something with arguments (a) put anything end </code></pre> <p>but that feels unsatisfactory for several reasons.</p> <p>I like the above solution because it uses a Struct instead of an OpenStruct, which means one less require, and what you get back is set as far as what variables are being handled.</p>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      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