On 8 Mar 2007, at 11:40, Gregory Brown wrote:
> On 3/8/07, Andrew Stewart <boss / airbladesoftware.com> wrote:
>> Hello,
>>
>> I'm wondering how I can ask a variable what its name is, so that I
>> can convert it into a symbol.
>>
>> For example, I'd like to convert @bar to :bar.
>
> You can't.  Variables aren't objects in Ruby.  However, if you post a
> bit of context of the actual problem, I bet folks here will be able to
> help you solve it.

Aha!  That explains why I couldn't.  Here's the context:

I have a line item object in memory (@line_item) and a set of line  
item attributes in a hash (keyed under params[:line_item]; this is in  
a Rails controller).  I only want to bother processing the line item  
hash if the quantity of either the in-memory object or the one in the  
hash is non-zero.

So I wrote this method:

   # TODO: the only reason for passing the symbol is that I don't know
   # how to convert the line_item's variable name into a symbol.
   def line_item_relevant(line_item, symbol)
     # Either we have an existing line item with non-zero quantity
     (line_item && line_item.quantity > 0) ||
     # Or we hearing about a line item with non-zero quantity
     (params[symbol] && params[symbol][:quantity] > 0)
   end

And I call it like this:

   ... if line_item_relevant @line_item_jacket, :line_item_jacket

And like this:

   ... if line_item_relevant @line_item_shirt,  :line_item_shirt

Et cetera.

It would be less repetitive if I could ditch the symbol argument to  
the method.  Hence my original question.

Any ideas would be welcome!

> You *can* get the listing of variables though:
>>> @foo = 10
> => 10
>>> instance_variables
> => ["@foo"]
>>> a = 3
> => 3
>>> local_variables
> => ["_", "__", "a"]

That's useful to know, thanks.

Regards,
Andy Stewart