Recently participated in the seven-cow demo contest, decided to use Ruby development. So I ran into some questions and then solved them, and here's a record.
In Ruby, Gem is a very common thing, it is the equivalent of Plug-ins, Ruby has a lot of great gems, to avoid the repetition of our wheels, my demo need to install gem, but in order to achieve better, first detect whether the gem has been installed, if not installed, continue to install, otherwise not installed.
So, how to detect gem in Ruby is installed, in fact, is also very simple, directly on the code can be. There is no need to explain too much. Begin...rescue ... Equivalent to a try catch in Java.
Copy Code code 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 up and have a look
Copy Code code as follows:
Puts checkgemavailable (' rack ')
Puts checkgemavailable (' rack ', ' >=2 ')
The rack information of my machine
Copy Code code as follows:
So the result of the above execution is
Copy Code code as follows: