# Understanding Ruby's defined? Keyword

*Published on March 14, 2024*

---


Ruby provides a handy&nbsp;`defined?(arg)`&nbsp;keyword that returns&nbsp;**a string describing its argument**.

```ruby
language = 'Ruby'

defined? language               # 'local-variable'
defined? @instance_var          # 'instance-variable'
defined? @@class_var            # 'class variable'

defined? nil                    # 'nil'

defined? 1                      # 'expression'
defined? 'Ruby'                 # 'expression'
defined? String                 # 'constant'
```

You can use&nbsp;`defined?`&nbsp;to test if the&nbsp;`expression`&nbsp;refers to anything recognizable. The&nbsp;`expression`&nbsp;can be an object, a variable, a method name, etc.

Note that a variable set to&nbsp;`nil`&nbsp;is still initialized and recognized by ruby as a&nbsp;`local-variable`.

```ruby
framework = nil

defined?(framework)  # 'local-variable'
```

However, if you pass an undefined variable,&nbsp;`defined?`&nbsp;returns&nbsp;`nil`. Similarly, if Ruby can’t resolve the expression, it returns&nbsp;`nil`.

```ruby
defined?(some_random_variable)  # nil
```

With the basics out of the way, let's look at a common usage pattern of this keyword.

## Usage: Lazy-Evaluation + Caching Expensive Operations

Sometimes, you want to lazily evaluate some code, only once. That is, do nothing if a variable exists but initialize it if it doesn’t.

The idiomatic ruby way to accomplish this is to use the&nbsp;`||=`&nbsp;operator.

```ruby
class Task
  def result
    @result ||= calculate_result
  end
  
  def calculate_result
    puts "heavy calculation here... should happen only once"
    
    100
  end
end

t = Task.new
puts t.result
puts t.result
puts t.result

# Output
#
# heavy calculation here... should happen only once
# 100
# 100
# 100
```

As you can see, calling the&nbsp;`result`&nbsp;method multiple times didn't call the expensive&nbsp;`calculate_result`&nbsp;method, since we had cached the result after the first call.

**It works... most of the time.**

If you have an expensive operation that can return&nbsp;`nil`&nbsp;or boolean value&nbsp;`false`&nbsp;as result, the cached method will be called each time you call&nbsp;`result`, eliminating the benefit of the&nbsp;`||=`&nbsp;operator.

For example, let's change the&nbsp;`calculate_result`&nbsp;method above to return&nbsp;`false`&nbsp;(or&nbsp;`nil`) instead of 100 and see what happens.

```ruby
class Task
  def result
    @result ||= calculate_result
  end
  
  def calculate_result
    puts "heavy calculation here... should happen only once"
    false  # or nil
  end
end

t = Task.new

puts t.result
puts t.result

# Output
#
# heavy calculation here... should happen only once
# false
# heavy calculation here... should happen only once
# false
```

After the first call,&nbsp;`@result`&nbsp;was&nbsp;`false`, a valid return value. Still, in later executions,&nbsp;**because**&nbsp;it evaluated to&nbsp;`false`, the Ruby interpreter called the expensive&nbsp;`calculate_result`&nbsp;method, which was unnecessary.

**In such cases, the**&nbsp;**`defined?`**&nbsp;**method comes in handy.**

Let's change the&nbsp;`result`&nbsp;method so it first checks if the&nbsp;`@result`&nbsp;variable is defined.

```ruby
def result
  return @result if defined?(@result)
  @result = calculate_result
end
```

Now, the&nbsp;`calculate_result`&nbsp;will be executed only once. For the subsequent calls, the instance variable&nbsp;`@result`&nbsp;is defined, so Ruby won't execute the second line of code above, skipping the expensive operation.

## Don’t use defined? to check hash keys

A common mistake is to use&nbsp;`defined?`&nbsp;to verify if a hash key is defined. Although Ruby devs might think it strange, this is especially common if you also write PHP on the side (like me - a big fan of&nbsp;[Laravel](https://laravel.com/)) and are used to the&nbsp;`isset()`&nbsp;method.

Consider the following example.

```ruby
hash = {}

if defined?(hash['random_key'])
  puts 'random_key exists'
else
  puts 'random_key missing'
end

# Output
# 
# 'random_key exists'
```

This is because the condition returned the string&nbsp;`'method'`, which ruby evaluates to&nbsp;`true`&nbsp;in a boolean expression.

```ruby
hash = {}

defined?(hash['random_key'])  # 'method'
```

The idiomatic Ruby way to check if a key exists in a hash is to use any of the following methods:&nbsp;`has_key?`,&nbsp;`key?`,&nbsp;`include?`, or&nbsp;`member?`

```ruby
hash = {}

if hash.include?('random_key')
  puts 'random_key exists'
else
  puts 'random_key missing'
end

# Output
# 
# 'random_key missing'
```

To learn more about the features and capabilities of a Ruby Hash, check out this article ([discussion](https://news.ycombinator.com/item?id=37202714)&nbsp;on Hacker News): [Ruby's Hash is a Swiss-Army Knife](/ruby-hash-is-a-swiss-army-knife)

## Should You use parenthesis with defined?

Since Ruby is so forgiving, you don’t always need to use parenthesis with&nbsp;`defined?`, but it’s highly recommended due to the low precedence of&nbsp;`defined?`&nbsp;keyword.

For example, the following test fails:

```ruby
class TestDefined < Minitest::Test
  def test_precedence
    result = 10
    assert_equal true, defined? result && result > 0
  end
end

# Fails!
# expected: true
# got: "expression"
```

Adding parentheses results in a better check, and it also results in a clear and readable code. The following test passes with flying colors.

```ruby
class TestDefined < Minitest::Test
  def test_precedence
    result = 10
    assert_equal true, defined?(result) && result > 0
  end
end
```

