top button
Flag Notify
Site Registration

How to get local variable name from object id or memory reference in ruby?

+1 vote
384 views

Follow the code :-

class Sample
 def bar
 p method(__method__).receiver # only `self` would do the trick.
 end
end

n1=Sample.new # => #
n2=Sample.new # => #

n1.bar # => #
n2.bar # => #

But this is my try. I am looking for any method is available in Ruby,into which say if I pas n1.object_id or #,I will get back in return the local variable name say here it is - n1 ?

posted Sep 6, 2013 by Bob Wise

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

I dont think that will be possible. A variable has an identifier ( in your case, n1 ) and a reference to an object ( Sample:0x13bc648 ) so when you say "n1" , it knows which object it references and returns that. As far as I know Ruby doesnt keep track of reference counts of an object and the object has no way of finding out which variable references itself.
But one inefficient way to achieve what you want would be to iterate through all the local variables and print the names of all local variables that has a particular object ID.

answer Sep 6, 2013 by Deepak Dasgupta
Similar Questions
+1 vote

In my local machine I had input some data into database using SQLite3 . When I deployed it to heroku why I can't get data that i input?

I'm doing like this

-in Gemfile
group :development do
 gem 'sqlite3'
end
group :production do
 gem 'pg'
 gem 'rails_12factor'
end
-bundle install
-heroku login
-git init 
-git add .
-git commit -m "test"
-git create
-git push heroku master
-heroku run rake db:migrate

How can I get some data when I deployed it to heroku? Please help me.

+1 vote

Is it possible to run Ruby and Rails on Mac OS X off of a local folder (without local or system install using RVM, Homebrew, etc.)

Similar to the way one can copy/paste Java installation directory and just run off of it with no dependencies, I'd like to do the same with Ruby/Rails.

The goal is to be able to connect a USB drive to someone's Mac OS X, open terminal, and demo an application (execute "rails server" from the mounted USB drive) without having to install/compile anything.

...