Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - print the variable name and then its value

What is the best way to write a function (or something DSLish) that will allow me to write this code in Ruby. How would I construct the function write_pair?

username = "tyndall" write_pair username # where write_pair username outputs  username: tyndall 

Is it possible to do? Looking for the most simple way to do this.

like image 684
BuddyJoe Avatar asked Apr 08 '10 21:04

BuddyJoe


People also ask

How do you get the value of a variable in Ruby?

NOTE − In Ruby, you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant.

How do you print a value in Ruby?

Everything in Ruby has a return value! You may notice that the puts and print methods, when run in IRB, print values on the screen and then display a line like this: => nil . This is because puts and print may print the value you want, but instead of returning that value, they return nil .

What is $_ in Ruby?

$_ is the last string read from IO by one of Kernel. gets , Kernel. readline or siblings. Pry introduces the underscore variable, returning the result of the last operation, on its own. It has nothing to do with ruby globals.

What is variable name in Ruby?

Ruby variables are locations which hold data to be used in the programs. Each variable has a different name. These variable names are based on some naming conventions. Unlike other programming languages, there is no need to declare a variable in Ruby.


1 Answers

Sure it is possible!

My solution tests the var by Object#object_id identity: http://codepad.org/V7TXRxmL
It's crippled in the binding passing style ...
Although it works just for local vars yet, it can be easily be made "universal" adding use of the other scope-variable-listing methods like instance_variables etc.

# the function must be defined in such a place  # ... so as to "catch" the binding of the vars ... cheesy # otherwise we're kinda stuck with the extra param on the caller @_binding = binding def write_pair(p, b = @_binding)   eval("     local_variables.each do |v|        if eval(v.to_s + \".object_id\") == " + p.object_id.to_s + "         puts v.to_s + ': ' + \"" + p.to_s + "\"       end     end   " , b) end  # if the binding is an issue just do here: # write_pair = lambda { |p| write_pair(p, binding) }  # just some test vars to make sure it works username1 = "tyndall" username  = "tyndall" username3 = "tyndall"  # the result: write_pair(username) # username: tyndall 
like image 80
12 revs, 3 users 92% Avatar answered Oct 10 '22 22:10

12 revs, 3 users 92%