So I know you can say Kernel.const_get(“ClassName”) and you’ll get back the class to which the string corresponds in name. But what about for variables? Is there a way to do:
test = "heyas"
some_method_here("test") #=> "heyas"
Thanks so much
The fact is that I need it in more complex code, real example:
class User
class Validations
class << self
def username_len
return u.len > 3 and u.len < 22
end
# ...
end
end
def validate(u,e,p)
[:u, :e, :p].each do |v|
Validations.send(:define_singleton_method, v, lambda { eval(v.to_s) }) # see this line
end
#other code to run validations
end
end
So you see, there’s no better way, is there?
No, there is only
class_variable_get,instance_variable_getandconst_get. There is nolocal_variable_get. But it wouldn’t make sense anyway: local variables are local to the current method body, module body, class body or script body, that’s why they are called “local” variables, after all! You simply cannot access them from another method.No, there is no way to do this. And there cannot possibly be a way to do it.
testis a local variable, which means it only exists in the current script body. It does not exist inside the body ofsome_method_here. That’s the whole point of local variables: you cannot ever, under any circumstances, access them from somewhere else.Regarding your comment on another answer:
Again, this cannot possibly work, since the whole point of local variables is that they cannot be accessed from anywhere else.
But there is a pretty simple variation which does exactly what you want:
This can of course be further simplified to:
Given that you can only pass in a limited number of different options, it’s probably better to use symbols instead:
What you are asking is basically: pass in a key, get a value out. That’s exactly what a
Hashis.EDIT: After the revised question, this is the best that I could come up with:
However, I think there is something seriously wrong with the design. You overwrite singleton methods of
User::Validationsbased on different instances ofUser. By the very definition of singleton method, there can only ever be one copy of those in the system. But you have many different instances ofUser, and every time you callUser#validateit will overwrite the only copies ofUser::Validations.u,User::Validations.eandUser::Validations.pat which point they will start to behave completely differently for the entire system.In other words, you are changing the behavior of the entire system based on a single instance. And there can be many instances and every time, the behavior of the system changes.
That just can’t be right.