ProGM
ProGM

Reputation: 7108

Check if local variable is defined given it's name as string in ruby

Can I check if a local variable is defined given it's name as string?

I know there is the function defined?, but you have to give the variable itself.

Example:

a = 'cat'
print defined?(a) # => "cat"
print defined?(b) # => nil

What I need is:

a = 'cat'
print string_defined?("a") # => "cat"
print string_defined?("b") # => nil

Or something like that. I can't find it in the docs...

I tried to use respond_to?, but doesn't seems to work...

Upvotes: 3

Views: 189

Answers (3)

sawa
sawa

Reputation: 168071

The following will return true when the local variable in question is (to be) defined in the context, not necessary in a position preceding the point of it:

local_variables.include?("a".to_sym)
#=> true

Upvotes: 4

Stefan
Stefan

Reputation: 114128

Starting with Ruby 2.1.0 you can use Binding#local_variable_defined?:

a = 'cat'
binding.local_variable_defined? 'a' #=> true
binding.local_variable_defined? 'b' #=> false

Upvotes: 4

Marek Lipka
Marek Lipka

Reputation: 51151

You can do it using eval:

a = 'cat'
eval("defined?(#{'a'})")
=> "local-variable"
eval("defined?(#{'b'})")
=> nil

Disclaimer: This answer makes use of eval, so it can be dangerous if you don't strictly control the string you want to pass into it. And definitely you shouldn't do it this way if these strings come from user input.

Upvotes: 3

Related Questions