rubygem中含有成千上万的第三方gem,网上书上扩展教程中都有指导如何使用第三方gem的例子。但是如果不幸这些例子都没有提及gem名称的话,如何只凭第三方类名或require名查找gem名称呢?换句话说,我怎么知道要intall神马gem呢?
举个例子来看《ruby之道》p60页有一个使用字符串压缩功能的第三方类,书上例子中有如下代码:
require ‘zlib’ include Zlib
真难为人啊!?我用gem search zlib -r搜索的结果如下:
apple@kissAir: ~$gem search zlib -r
*** REMOTE GEMS ***
ffi-zlib (0.2.0)
pr-zlib (1.0.0)
rubysl-zlib (2.0.1)
sprout-fzlib-library (1.0.0)
zlib-crc32_combine (1.0.2)
zlib-socs (0.1)
Zliby (0.0.5)
zliby (0.0.5)
到底应该用哪个呢?这个真不好说,那么到http://ruby-doc.com/gems去看看吧!我们当然选择Z开头的gem,找到Zliby比较像,进去看看,发现含有Zlib模块,我才zliby和Zliby是一码事(他们版本号都一样哎)我们就用zliby啦:
gem install zliby -r
很快gem安装完毕,下面上测试代码:
#!/usr/bin/ruby require 'zlib' include Zlib str = ("aa0".."zz9").to_a.join*1000 puts "str.size is #{str.size}" class Deflate class << self alias old_deflate deflate def deflate(str,level=DEFAULT_COMPRESSION) t = Time.now s=old_deflate(str,level) puts "#{__callee__} takes #{Time.now - t}s" s end end end #压缩 s1 = Deflate.deflate(str,BEST_SPEED) s2 = Deflate.deflate(str) s3 = Deflate.deflate(str,BEST_COMPRESSION) puts "s1.size:#{s1.size} s2.size:#{s2.size} s3.size:#{s3.size}" #解压缩 us = Inflate.inflate(s3) puts "us.size is #{us.size}" puts "#{us == str}"
为了计算deflate方法运行时间,我重写了该方法,并在其中调用原来的方法。最后是运行结果:
apple@kissAir: ruby_src$./dzh.rb
str.size is 20280000
deflate takes 0.075283s
deflate takes 0.154147s
deflate takes 0.166407s
s1.size:276965 s2.size:160761 s3.size:160761
us.size is 20280000
true