Ruby - print the variable name and then its value

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

    This is a simple solution:

      def write_pair(variable)
        puts variable + eval(variable)
      end
    

    This is more readable:

     def write_pair(variable)
        puts 'A' * 100
        puts variable + ': ' + eval(variable).inspect
        puts 'Z' * 100
     end
    

    Invocation:

    write_pair "variable"
    

提交回复
热议问题