which for Ruby
30分プログラム、その154。Ruby用のWhich。
requireしているファイルが、実際はどこに置いてあるかを調べてくれる。標準ライブラリの中を除いたり、Rubygemsで入れたライブラリを取り出したりするときに便利。
久しぶりに、必要に迫られて作ったプログラム。
使い方
$ ruby rwhich.rb time /opt/local/lib/ruby/1.8/time.rb $ ruby rwhich.rb json /opt/local/lib/ruby/gems/1.8/gems/json_pure-1.1.0/lib/json
ソースコード
#! /opt/local/bin/ruby -w # -*- mode:ruby; coding:utf-8 -*- # # rwhich.rb - whcih command for Ruby Library # # Copyright(C) 2007 by mzp # Author: MIZUNO Hiroki <hiroki1124@gmail.com> # http://mzp.sakura.ne.jp/ # # Timestamp: 2007/10/13 20:26:08 # # This program is free software; you can redistribute it and/or # modify it under the same terms as Ruby itself. # def find_file(name) begin # いったんrequireするとGemsのやつも探せるようになる require name $:.map{|base| [File.expand_path(name,base), File.expand_path(name+'.so',base), File.expand_path(name+'.rb',base)] }.flatten.find{|path| File.exist? path } rescue [] end end def which(*names) names.map(&method(:find_file)) end if __FILE__ == $0 then puts which(*ARGV) end
参考
- 過去の30分プログラム
- プログラミング言語 Ruby リファレンスマニュアル - requireの説明