Ruby - print the variable name and then its value

前端 未结 8 2180
梦毁少年i
梦毁少年i 2020-11-27 05:35

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?

         


        
8条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 06:01

    def write_pair var, binding
      puts "#{ var } = #{ eval(var, binding)}"
    end
    
    
    username = "tyndall"
    write_pair "username", binding
    

    This seems weird because binding is never defined, but it works. From Ruby: getting variable name:

    The binding() method gives a Binding object which remembers the context at the point the method was called. You then pass a binding into eval(), and it evaluates the variable in that context.

    Be sure to pass a string, not the variable.

提交回复
热议问题