Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I don't believe there's any way to do this in Ruby (if anyone comes up with one, please let me know, and I'll update or delete this answer to reflect it!) - if a local variable hasn't been defined yet, there's no way to dynamically define it with the binding. You could conceivably do something like <code>orange, lemon, grapefruit = nil</code> before calling eval, but you may run into other problems - for instance, if args[:orange] is the string "Orange", you'll end up evaluating <code>orange = Orange</code> with your current implementation.</p> <p>Here's something that could work, though, using the <a href="http://ruby-doc.org/stdlib/libdoc/ostruct/rdoc/classes/OpenStruct.html" rel="nofollow noreferrer">OpenStruct</a> class from the standard library (by "could work", I mean "it's up to your sense of style whether <code>a.orange</code> is any nicer than <code>args[:orange]</code>"):</p> <pre><code>require 'ostruct' def my_method_with_ostruct(args) a = OpenStruct.new(args) puts "my_method_with_ostruct variables: #{a.orange}, #{a.lemon}, #{a.grapefruit}" end </code></pre> <p>If you don't need easy access to any state or methods on the receiver of this method, you could use <a href="http://ruby-doc.org/core/classes/Object.html#M000334" rel="nofollow noreferrer">instance_eval</a>, as follows.</p> <pre><code>def my_method_with_instance_eval(args) OpenStruct.new(args).instance_eval do puts "my_method_with_instance_eval variables: #{orange}, #{lemon}, #{grapefruit}" end end </code></pre> <p>You could even do <a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/19153" rel="nofollow noreferrer">something tricky with method_missing</a> (see <a href="http://www.dcmanges.com/blog/ruby-dsls-instance-eval-with-delegation" rel="nofollow noreferrer">here</a> for more) to allow access to the "primary" object, but the performance probably wouldn't be great.</p> <p>All in all, I think it's probably most straightforward/readable to go with the less DRY initial solution that bothered you.</p>
 

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