get instance variable name from itself in ruby

后端 未结 4 1027
花落未央
花落未央 2021-01-13 11:43

I have an instance variable @foo and I want to write some code so that I get string \'foo\'

any hint?

4条回答
  •  一生所求
    2021-01-13 12:19

    class Object
        def get_name
          line_number = caller[0].split(':')[1].to_i
          line_exectued = File.readlines( __FILE__)[line_number-1]
          line_exectued.match(/(\S+).get_name/)[1]
        end
    end
    
    inconceivable = true
    
    p inconceivable.get_name
    

提交回复
热议问题