art with code

2008-08-27

Most-used file methods in Ruby (plus some stats on arrays, strings and hashes)

I.e. how many times a method was written in all the Ruby files on my system.

Results:

File.join 4038
File.dirname 2850
File.basename 2399
File.open 2385
File.exist 2020
File.expand_path 1899
File.read 1039
File.dir 1024
File.file 786
File.unlink 574

FileUtils.mkdir_p 368
FileUtils.rm_rf 185
FileUtils.mv 85
FileUtils.rm_r 77
FileUtils.touch 57
FileUtils.cp 56
FileUtils.ln_s 49
FileUtils.cp_r 47
FileUtils.mkdir 44
FileUtils.verbose_flag 40

f.read 1231
f.puts 707
f.write 689
f.flock 302
f.seek 293
f.name 264
f.pos 162
f.gets 134
f.stat 117
f.close 102


How about s[trings], a[rrays] and h[ashtables]?

s.to_s 349
s.scan 279
s.split 222
s.empty 170
s.rb 152
s.last 124
s.gsub 120
s.nil 120
s.size 118
s.to_f 91

a.size 186
a.to_s 175
a.include 151
a.slice 130
a.each 125
a.inspect 108
a.token_stream 97
a.class 92
a.b 89
a.kind_of 85

h.delete 382
h.clone 127
h.keys 118
h.each 109
h.to_f 99
h.merge 93
h.empty 47
h.values 45
h.to_json 42
h.call 41


How-to:

def mk_hash; Hash.new{|h,k|h[k]=0}; end
hashes = %W(File FileUtils f s a h).map{|n| [n, mk_hash] }

ruby_files = `locate '*.rb'`.split("\n")
ruby_files.each{|f|
d = File.read(f)
hashes.each{|name, hash|
d.scan(/\b#{name}[\.:]+[a-z0-9_]+/).each{|k|
hash[k.split(/[\.:]+/).join(".")] += 1
}
}
}
hashes.each do |n, h|
File.open(n+".txt", "w"){|f|
f.puts h.to_a.sort_by{|k,v| -v}.map{|k,v| k.ljust(25) + " " + v.to_s }
}
end

No comments:

Blog Archive