Ruby Language Gem Usage Checking if a required gem is installed from within code

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

To check if a required gem is installed, from within your code, you can use the following (using nokogiri as an example):

begin
  found_gem = Gem::Specification.find_by_name('nokogiri')
  require 'nokogiri'
  ....
  <the rest of your code>
rescue Gem::LoadError
end

However, this can be further extended to a function that can be used in setting up functionality within your code.

def gem_installed?(gem_name)
  found_gem = false
  begin
    found_gem = Gem::Specification.find_by_name(gem_name)
  rescue Gem::LoadError
     return false
  else
    return true
  end
end

Now you can check if the required gem is installed, and print an error message.

if gem_installed?('nokogiri')
  require 'nokogiri'
else
  printf "nokogiri gem required\n"
  exit 1
end

or

if gem_installed?('nokogiri')
  require 'nokogiri'
else
  require 'REXML'
end


Got any Ruby Language Question?