views:

30

answers:

2

From example:

local_var = "Thanks!"
@instance_var = "Thank you ,too"

Then how can I get the local_var and instance_var part by them self. I mean weather there is a method maybe called get_self_name to get the name of himself:

local_var.get_self_name # => 'local_var'
@instance_var.get_self_name # => '@instance_var' or => 'instance_var'

a = 'abc'
a.get_self_name # => 'a'
+1  A: 
$ irb
>> local_var = "foo"
=> "foo"
>> @instance_var = "bar"
=> "bar"
>> instance_variables
=> ["@prompt", "@instance_var"]
>> local_variables
=> ["_", "local_var"]

You also may want to check out ObjectSpace module.

The _ local variable is automatically set to returned value of the last irb statement. @prompt is probably irb's prompt format or something similar.

Eimantas
Thank you, too. And thanks for you editing.
Croplio
+1  A: 

There is no method that can do that. Here are some ways to get around it:

-1- Use a hash:

local_var = "Thanks!"
@instance_var = "Thank you ,too"
hash = {
  local_var: local_var,
  instance_var: @instance_var
}

hash.index(@instance_var) #=> :instance_var

-2- use instance_variables:

local_var = "Thanks!"
@instance_var = "Thank you ,too"

instance_variables.find {|x| instance_variable_get(x) == @instance_var } #=> :instance_var

Note that this won't work for local variables.

Adrian
Thank u very much, help a lot!
Croplio
It seems that we can get local variable use the second method:local_var = "Thanks!";local_variables.find { |x| eval(x.to_s) == local_var}
Croplio