Method to determine if a variable already exists or not

Asked 2 years ago, Updated 2 years ago, 33 views

Which method should we use to find out if a variable already exists or not in Ruby?

For example,

a = 3

isset? a #true
isset? v #false

I'm looking for a method that returns true only when it's a variable that I'm already writing in this way

ruby

2022-09-22 22:05

1 Answers

There is a defined? keyword that performs this function.

#defined?

defined? expression tests whether or not expression refers to anything recognizable (literal object, local variable that has been initialized, method name visible from the current scope, etc.). The return value is nil if the expression cannot be resolved. Otherwise, the return value provides information about the expression.

Test whether the given expression is recognizable or not. If the expression cannot be resolved, it returns nil, otherwise it returns information related to the expression.

>> a = 1
 => 1
>> defined? a
 => "locdal-variable"
>> defined? b
 => nil
>> defined? nil
 => "nil"
>> defined? String
 => "constant"
>> defined? 1
 => "expression"


2022-09-22 22:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.