How to get a variable name?

Asked

Viewed 55 times

0

Is there any way to get the name of a variable using metaprogramming (or reflection, I believe) in Ruby? I want something like nameof of the C#.

I was looking for something like:

minha_variavel = "valor"
minha_variavel.name
=> "minha_variavel"

I tried to use several methods, but without success. I even used the Object#object_id to work with the object, but I didn’t get the result I expected:

ObjectSpace._id2ref(minha_variavel.object_id)
=> "valor"

The ObjectSpace#_id2ref gets the instance itself, which is evaluated by its value. What I want is the name assigned to the object.

Is it possible? If not, what makes it impossible, whether in other languages this type of situation can be resolved?

  • Out of curiosity, is there any practical application in getting the name of a variable? Something to do nameof(var) instead of just "var"?

  • 1

    An application would be logging. Maybe save rework. And variables, classes or the like can be created dynamically in some contexts @Andersoncarloswoss

  • 1

    I don’t think Ruby has this Feature because it seems to be unnecessary in scripting languages (Languages script), which is not the case for C# which is compiled and the reference to the name of the variables changes in binary. See this answer on the nameof. And to logging I believe that the Kernel#set_trac_func is sufficient. (And of course if you have an actual example of the nameof applied to logging with Ruby would be very helpful)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.