Ruby - print the variable name and then its value

前端 未结 8 2176
梦毁少年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 05:57

    Building on previous answers relating to symbols & bindings ... if passing in the variable name as a symbol works for you (who doesn't love cutting out extra keystrokes?!), try this:

    def wp(var_name_as_sym)
      # gets caller binding, which contains caller's execution environment
      parent_binding = RubyVM::DebugInspector.open{|i| i.frame_binding(2) }
      # now puts the symbol as string + the symbol executed as a variable in the caller's binding
      puts %Q~#{var_name_as_sym.to_s} = #{eval("#{var_name_as_sym.to_s}.inspect", parent_binding)}~
    end
    
    aa=1
    bb='some bb string'
    os = OpenStruct.new(z:26, y:25)
    

    Console output:

    > wp :aa
    aa = 1
    => nil
    > wp :bb
    bb = "some bb string"
    => nil
    > wp :os
    os = #
    => nil
    

    Using ruby 2.2.2p95

    (Credit to banister for getting binding of calling context)

提交回复
热议问题