Ruby - print the variable name and then its value

前端 未结 8 2238
梦毁少年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:47

    # make use of dynamic scoping via methods and instance vars
    @_binding = binding
    def eval_debug(expr, binding = @_binding)
       "#{expr} => #{eval(expr, binding)}"
    end
    
    # sample invocation:
    x = 10
    puts eval_debug "x"
    puts eval_debug "x**x"
    

提交回复
热议问题