Ruby - print the variable name and then its value

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

    If it's possible for you to use a symbol instead of the variable name, you could do something like this:

    def wp (s, &b)
      puts "#{s} = #{eval(s.to_s, b.binding)}"
    end
    

    In use:

    irb(main):001:0> def wp (s, &b)
    irb(main):002:1>   puts "#{s} = #{eval(s.to_s, b.binding)}"
    irb(main):003:1> end
    => nil
    irb(main):004:0> var = 3
    => 3
    irb(main):005:0> wp(:var) {}
    var = 3
    

    Note that you must pass the empty block {} to the method or it cannot get the binding to evaluate the symbol.

提交回复
热议问题