Ruby - print the variable name and then its value

前端 未结 8 2071
梦毁少年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.

    0 讨论(0)
  • 2020-11-27 06:06

    I made a vim macro for this:

    " Inspect the variable on the current line (in Ruby)
    autocmd FileType ruby nmap ,i ^"oy$Iputs "<esc>A: #{(<esc>"opA).inspect}"<esc>
    

    Put the variable you'd like to inspect on a line by itself, then type ,i (comma then i) in normal mode. It turns this:

    foo
    

    into this:

    puts "foo: #{(foo).inspect}"
    

    This is nice because it doesn't have any external dependencies (e.g. you don't have to have a library loaded up to use it).

    0 讨论(0)
提交回复
热议问题