<p>I'm not entirely sure if this is possible in Ruby, but hopefully there's an easy way to do this. I want to declare a variable and later find out the name of the variable. That is, for this simple snippet:</p>

<pre><code>foo = ["goo", "baz"]
</code></pre>

<p>How can I get the name of the array (here, "foo") back? If it is indeed possible, does this work on any variable (e.g., scalars, hashes, etc.)?</p>

<p>Edit: Here's what I'm basically trying to do. I'm writing a SOAP server that wraps around a class with three important variables, and the validation code is essentially this:</p>

<pre><code>  [foo, goo, bar].each { |param|
      if param.class != Array
        puts "param_name wasn't an Array. It was a/an #{param.class}"
        return "Error: param_name wasn't an Array"
      end
      }
</code></pre>

<p>My question is then: Can I replace the instances of 'param_name' with foo, goo, or bar? These objects are all Arrays, so the answers I've received so far don't seem to work (with the exception of re-engineering the whole thing ala <a href="https://stackoverflow.com/questions/58482/ruby-get-a-variables-name#58870">dbr's answer</a>) </p>

[{'answer_id': 58492, 'author': 'Josh Moore', 'author_id': 5004, 'author_profile': 'https://Stackoverflow.com/users/5004', 'pm_score': 2, 'selected': False, 'text': '<p>I do not know of any way to get a local variable name.  But, you can use the <code>instance_variables</code> method, this will return an array of all the instance variable names in the object.  </p>\n\n<p>Simple call:</p>\n\n<pre><code>object.instance_variables\n</code></pre>\n\n<p>or</p>\n\n<pre><code>self.instance_variables\n</code></pre>\n\n<p>to get an array of all instance variable names.</p>\n'}, {'answer_id': 58734, 'author': 'James A. Rosen', 'author_id': 1190, 'author_profile': 'https://Stackoverflow.com/users/1190', 'pm_score': 2, 'selected': False, 'text': '<p>Building on <a href="https://stackoverflow.com/users/5004/joshsmooremyopenidcom">joshmsmoore</a>, something like this would probably do it:</p>\n\n<pre><code># Returns the first instance variable whose value == x\n# Returns nil if no name maps to the given value\ndef instance_variable_name_for(x)\n  self.instance_variables.find do |var|\n    x == self.instance_variable_get(var)\n  end\nend\n</code></pre>\n'}, {'answer_id': 58765, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 2, 'selected': False, 'text': "<p>There's <code>Kernel::local_variables</code>, but I'm not sure that this will work for a method's local vars, and I don't know that you can manipulate it in such a way as to do what you wish to acheive.</p>\n"}, {'answer_id': 58830, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 3, 'selected': False, 'text': '<p>OK, it DOES work in instance methods, too, and, based on your specific requirement (the one you put in the comment), you could do this:</p>\n\n<pre><code>local_variables.each do |var|\n  puts var if (eval(var).class != Fixnum)\nend\n</code></pre>\n\n<p>Just replace <code>Fixnum</code> with your specific type checking.</p>\n'}, {'answer_id': 58870, 'author': 'dbr', 'author_id': 745, 'author_profile': 'https://Stackoverflow.com/users/745', 'pm_score': 3, 'selected': False, 'text': '<p>It seems you are trying to solve a problem that has a far easier solution..</p>\n\n<p>Why not just store the data in a hash? If you do..</p>\n\n<pre><code>data_container = {\'foo\' =&gt; [\'goo\', \'baz\']}\n</code></pre>\n\n<p>..it is then utterly trivial to get the \'foo\' name.</p>\n\n<p>That said, you\'ve not given any context to the problem, so there may be a reason you can\'t do this..</p>\n\n<p><em>[edit]</em> After clarification, I see the issue, but I don\'t think this is the problem.. With [foo, bar, bla], it\'s equivalent like saying <code>[\'content 1\', \'content 2\',  \'etc\']</code>. The actual variables name is (or rather, should be) utterly irrelevant. If the name of the variable is important, that is exactly why hashes exist.</p>\n\n<p>The problem isn\'t with iterating over [foo, bar] etc, it\'s the fundamental problem with how the SOAP server is returing the data, and/or how you\'re trying to use it.</p>\n\n<p>The solution, I would say, is to either make the SOAP server return hashes, or, since you know there is always going to be three elements, can you not do something like..</p>\n\n<pre><code>{"foo" =&gt; foo, "goo" =&gt; goo, "bar"=&gt;bar}.each do |param_name, param|\n      if param.class != Array\n        puts "#{param_name} wasn\'t an Array. It was a/an #{param.class}"\n        puts "Error: #{param_name} wasn\'t an Array"\n      end\nend\n</code></pre>\n'}, {'answer_id': 59259, 'author': 'pauliephonic', 'author_id': 5374, 'author_profile': 'https://Stackoverflow.com/users/5374', 'pm_score': 1, 'selected': False, 'text': "<p>You can't, you need to go back to the drawing board and re-engineer your solution.</p>\n"}, {'answer_id': 61729, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 5, 'selected': False, 'text': '<p>You need to re-architect your solution. Even if you <em>could</em> do it (you can\'t), the question simply doesn\'t have a reasonable answer.</p>\n\n<p>Imagine a get_name method.</p>\n\n<pre><code>a = 1\nget_name(a)\n</code></pre>\n\n<p>Everyone could probably agree this should return \'a\'</p>\n\n<pre><code>b = a\nget_name(b)\n</code></pre>\n\n<p>Should it return \'b\', or \'a\', or an array containing both?</p>\n\n<pre><code>[b,a].each do |arg|\n  get_name(arg)\nend\n</code></pre>\n\n<p>Should it return \'arg\', \'b\', or \'a\' ?</p>\n\n<pre><code>def do_stuff( arg )\n  get_name(arg)\ndo\ndo_stuff(b)\n</code></pre>\n\n<p>Should it return \'arg\', \'b\', or \'a\', or maybe the array of all of them? Even if it did return an array, what would the order be and how would I know how to interpret the results?</p>\n\n<p>The answer to all of the questions above is "It depends on the particular thing I want at the time." I\'m not sure how you could solve that problem for Ruby.</p>\n'}, {'answer_id': 63523, 'author': 'glenn mcdonald', 'author_id': 7919, 'author_profile': 'https://Stackoverflow.com/users/7919', 'pm_score': 6, 'selected': True, 'text': '<p>What if you turn your problem around? Instead of trying to get names from variables, get the variables from the names:</p>\n\n<pre><code>["foo", "goo", "bar"].each { |param_name|\n  param = eval(param_name)\n  if param.class != Array\n    puts "#{param_name} wasn\'t an Array. It was a/an #{param.class}"\n    return "Error: #{param_name} wasn\'t an Array"\n  end\n  }\n</code></pre>\n\n<p>If there were a chance of one the variables not being defined at all (as opposed to not being an array), you would want to add "rescue nil" to the end of the "param = ..." line to keep the eval from throwing an exception...</p>\n'}, {'answer_id': 66517, 'author': 'Michael Latta', 'author_id': 9679, 'author_profile': 'https://Stackoverflow.com/users/9679', 'pm_score': 1, 'selected': False, 'text': "<p>Foo is only a location to hold a pointer to the data.  The data has no knowledge of what points at it.  In Smalltalk systems you could ask the VM for all pointers to an object, but that would only get you the object that contained the foo variable, not foo itself.  There is no real way to reference a vaiable in Ruby.  As mentioned by one answer you can stil place a tag in the data that references where it came from or such, but generally that is not a good apporach to most problems.  You can use a hash to receive the values in the first place, or use a hash to pass to your loop so you know the argument name for validation purposes as in DBR's answer.</p>\n"}, {'answer_id': 67910, 'author': 'Greg Borenstein', 'author_id': 10419, 'author_profile': 'https://Stackoverflow.com/users/10419', 'pm_score': 1, 'selected': False, 'text': '<p>The closest thing to a real answer to you question is to use the Enumerable method each_with_index instead of each, thusly:</p>\n\n<pre><code>my_array = [foo, baz, bar]\nmy_array.each_with_index do |item, index|\n  if item.class != Array\n    puts "#{my_array[index]} wasn\'t an Array. It was a/an #{item.class}"\n  end\nend\n</code></pre>\n\n<p>I removed the return statement from the block you were passing to each/each_with_index because it didn\'t do/mean anything. Each and each_with_index both return the array on which they were operating.</p>\n\n<p>There\'s also something about scope in blocks worth noting here: if you\'ve defined a variable outside of the block, it will be available within it. In other words, you could refer to foo, bar, and baz directly inside the block. The converse is not true: variables that you create for the first time inside the block will not be available outside of it.</p>\n\n<p>Finally, the do/end syntax is preferred for multi-line blocks, but that\'s simply a matter of style, though it is universal in ruby code of any recent vintage.</p>\n'}, {'answer_id': 17029573, 'author': 'Boris Stitnicky', 'author_id': 1153747, 'author_profile': 'https://Stackoverflow.com/users/1153747', 'pm_score': 2, 'selected': False, 'text': '<p>Great question. I fully understand your motivation. Let me start by noting, that there are certain kinds of special objects, that, under certain circumstances, have knowledge of the variable, to which they have been assigned. These special objects are eg. <code>Module</code> instances, <code>Class</code> instances and <code>Struct</code> instances:</p>\n\n<pre><code>Dog = Class.new\nDog.name # Dog\n</code></pre>\n\n<p>The catch is, that this works only when the variable, to which the assignment is performed, is a constant. (We all know that Ruby constants are nothing more than emotionally sensitive variables.) Thus:</p>\n\n<pre><code>x = Module.new # creating an anonymous module\nx.name #=&gt; nil # the module does not know that it has been assigned to x\nAnimal = x # but will notice once we assign it to a constant\nx.name #=&gt; "Animal"\n</code></pre>\n\n<p>This behavior of objects being aware to which variables they have been assigned, is commonly called <em>constant magic</em> (because it is limited to constants). But this highly desirable <em>constant magic</em> only works for certain objects:</p>\n\n<pre><code>Rover = Dog.new\nRover.name #=&gt; raises NoMethodError\n</code></pre>\n\n<p>Fortunately, <a href="https://github.com/boris-s/y_support" rel="nofollow">I have written a gem <code>y_support/name_magic</code></a>, that takes care of this for you:</p>\n\n<pre><code> # first, gem install y_support\nrequire \'y_support/name_magic\'\n\nclass Cat\n  include NameMagic\nend\n</code></pre>\n\n<p>The fact, that this only works with constants (ie. variables starting with a capital letter) is not such a big limitation. In fact, it gives you freedom to name or not to name your objects at will:</p>\n\n<pre><code>tmp = Cat.new # nameless kitty\ntmp.name #=&gt; nil\nJosie = tmp # by assigning to a constant, we name the kitty Josie\ntmp.name #=&gt; :Josie\n</code></pre>\n\n<p>Unfortunately, this will not work with array literals, because they are internally constructed without using <code>#new</code> method, on which <code>NameMagic</code> relies. Therefore, to achieve what you want to, you will have to subclass <code>Array</code>:</p>\n\n<pre><code>require \'y_support/name_magic\'\nclass MyArr &lt; Array\n  include NameMagic\nend\n\nfoo = MyArr.new ["goo", "baz"] # not named yet\nfoo.name #=&gt; nil\nFoo = foo # but assignment to a constant is noticed\nfoo.name #=&gt; :Foo\n\n# You can even list the instances\nMyArr.instances #=&gt; [["goo", "baz"]]\nMyArr.instance_names #=&gt; [:Foo]\n\n# Get an instance by name:\nMyArr.instance "Foo" #=&gt; ["goo", "baz"]\nMyArr.instance :Foo #=&gt; ["goo", "baz"]\n\n# Rename it:\nFoo.name = "Quux"\nFoo.name #=&gt; :Quux\n\n# Or forget the name again:\nMyArr.forget :Quux\nFoo.name #=&gt; nil\n\n# In addition, you can name the object upon creation even without assignment\nu = MyArr.new [1, 2], name: :Pair\nu.name #=&gt; :Pair\nv = MyArr.new [1, 2, 3], ɴ: :Trinity\nv.name #=&gt; :Trinity\n</code></pre>\n\n<p>I achieved the constant magic-imitating behavior by <em>searching all the constants in all the namespaces</em> of the current Ruby object space. This wastes a fraction of second, but since the search is performed only once, there is no performance penalty once the object figures out its name. In the future, Ruby core team <a href="http://bugs.ruby-lang.org/issues/7149" rel="nofollow">has promised <code>const_assigned</code> hook</a>.</p>\n'}]
['https://Stackoverflow.com/questions/58482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/422/']