How to check whether the Gem is installed in Ruby.

Source: Internet
Author: User
Tags try catch

How to check whether the Gem is installed in Ruby.

I recently participated in the 7won demo competition and decided to use ruby for development. So I encountered some questions and solved them. Record them here.

In Ruby, Gem is a very common thing. It is equivalent to a plug-in. Ruby has a lot of great gem, which prevents us from repeating the wheel. In my demo, We need to install gem, however, to make the installation better, first check whether the gem has been installed. If it is not installed, continue the installation; otherwise, do not install it.

So, how can we check whether the gem is installed in Ruby? In fact, it is also very simple, just go to the code. You do not need to explain it too much. Begin... Rescue... It is equivalent to try catch in java.

Copy codeThe Code is as follows:
#! /Usr/bin/env ruby
# Encoding: UTF-8

Def checkGemAvailable (gemName, versionLimit = nil)
IsAvailable = false
Begin
If versionLimit = nil
Gem gemName
Else
Gem gemName, versionLimit
End
IsAvailable = true
Rescue LoadError
End
IsAvailable
End

Run and have a look

Copy codeThe Code is as follows:
Puts checkGemAvailable ('rack ')
Puts checkGemAvailable ('rack', '> = 2 ')

Rack information of my machine

Copy codeThe Code is as follows:
Rack (1.5.2)

Therefore, the execution result above is

Copy codeThe Code is as follows:
True
False

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.