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