Ruby - print the variable name and then its value

前端 未结 8 2167
梦毁少年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条回答
  •  -上瘾入骨i
    2020-11-27 05:42

    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
    

提交回复
热议问题