Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

ruby - Is there a 'variable_get' method? If not, how can I create my own?

courtesy of irb:

2.0.0-p0 :006 > @instance_variable = "from an instance variable"
 => "from an instance variable" 
2.0.0-p0 :007 > variable = "from a variable"
 => "from a variable" 
2.0.0-p0 :008 > instance_variable_get(:@instance_variable)
 => "from an instance variable" 
2.0.0-p0 :009 > variable_get(:variable)
NoMethodError: undefined method `variable_get' for main:Object
    from (irb):9
    from /usr/local/rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in `<main>'
2.0.0-p0 :010 > 

I'm simply trying to programmatically 'query' for a variable and return its contents. Exactly like instance_variable_get but for a variable.

It's for a custom rspec matcher. Not some crazy workaround :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Ruby 2.1 and later, you can use Binding#local_variable_get.

In prior versions of Ruby, you have to use eval. If you want to do some sanity-checking before evaluating a supposed variable name, you can check whether the named variable is in local_variables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...