# Compare Strings Using Inquiry

*Published on September 30, 2022*

---


Similar to the&nbsp;[ArrayInquirer](/array-inquirer-in-rails)&nbsp;class, which tests if an array contains a value, the `ActiveSupport::StringInquirer`&nbsp;class provides a nice way to compare two strings. Use it when you have an internal method that returns a string, and the consumer of that method needs to compare it with another string.

```ruby
def env
  ActiveSupport::StringInquirer.new('production')
end

env.production? # true
env.local?      # false
```

Behind the scenes, implementing this needs some metaprogramming, as Rails can't know the value of the string in advance. &nbsp;

```ruby
def method_missing(method_name, *arguments)
  if method_name.end_with?("?")
    self == method_name[0..-2]
  else
    super
  end
end
```

The Ruby interpreter calls the&nbsp;`method_missing`&nbsp;method when it can't find the invoked method. If the method name ends with a&nbsp;`?`, &nbsp;it compares the original string with the method's name minus the&nbsp;`?`.

## The 'inquiry' Shortcut

Rails further simplifies it by adding the&nbsp;`inquiry`&nbsp;extension method on&nbsp;`String`&nbsp;which returns an instance of the&nbsp;`StringInquirer`&nbsp;class.

```ruby
def env
  'production'.inquiry
end

env.production? # true
env.local?      # false
```

Here's the implementation of the&nbsp;`String#inquiry`&nbsp;method. It instantiates the&nbsp;`StringInquirer`&nbsp;class, passing&nbsp;`self`&nbsp;which is the string itself.

```ruby
# activesupport/lib/active_support/core_ext/string/inquiry.rb

class String
  def inquiry
    ActiveSupport::StringInquirer.new(self)
  end
end
```

I love how much Rails cares about beautiful code and goes above and beyond to simplify its external API.

Hope you learned something new.&nbsp;[Let me know](mailto:akshay.khot@hey.com)&nbsp;if you liked this post or have any feedback. I look forward to hearing from you.

