Access variables programmatically by name in Ruby

后端 未结 11 926
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 19:15

I\'m not entirely sure if this is possible in Ruby, but hopefully there\'s an easy way to do this. I want to declare a variable and later find out the name of the variable.

11条回答
  •  甜味超标
    2020-11-27 19:45

    You need to re-architect your solution. Even if you could do it (you can't), the question simply doesn't have a reasonable answer.

    Imagine a get_name method.

    a = 1
    get_name(a)
    

    Everyone could probably agree this should return 'a'

    b = a
    get_name(b)
    

    Should it return 'b', or 'a', or an array containing both?

    [b,a].each do |arg|
      get_name(arg)
    end
    

    Should it return 'arg', 'b', or 'a' ?

    def do_stuff( arg )
      get_name(arg)
    do
    do_stuff(b)
    

    Should it return 'arg', 'b', or 'a', or maybe the array of all of them? Even if it did return an array, what would the order be and how would I know how to interpret the results?

    The answer to all of the questions above is "It depends on the particular thing I want at the time." I'm not sure how you could solve that problem for Ruby.

提交回复
热议问题