From: Ryan Davis Date: 2008-02-07T14:16:14+09:00 Subject: Re: idiom I've not seen before On Feb 6, 2008, at 20:04 , Rob Biedenharn wrote: > You've found Symbol#to_proc > > That line is equivalent to: > > elements.sort_by {|e| e.send(:position) }.each Buyer beware: #!/usr/local/bin/ruby -w # # of iterations = 10000 # user system total real # null_time 0.000000 0.000000 0.000000 ( 0.001561) # map 0.880000 0.000000 0.880000 ( 0.878500) # to_proc 2.790000 0.000000 2.790000 ( 2.799291) # # of iterations = 100000 # user system total real # null_time 0.020000 0.000000 0.020000 ( 0.013951) # map 8.730000 0.010000 8.740000 ( 8.766693) # to_proc 27.960000 0.030000 27.990000 ( 28.001288) require 'benchmark' class Symbol def to_proc Proc.new { |*args| args.shift.__send__(self, *args) } end end a = (1..100).to_a raise "stupid" unless a.map { |n| n.to_s } == a.map(&:to_s) max = (ARGV.shift || 1_000_000).to_i puts "# of iterations = #{max}" Benchmark::bm(20) do |x| x.report("null_time") do for i in 0..max do # do nothing end end x.report("map") do for i in 0..max do a.map { |n| n.to_s } end end x.report("to_proc") do for i in 0..max do a.map(&:to_s) end end end