From: Aldric Giacomoni Date: 2009-11-20T03:35:11+09:00 Subject: Re: Re-opening an existing module and changing a method Marnen Laibow-Koser wrote: > > Looks fine to me. Does old_sqrt actually return a Float or some other > numeric type? > > Actually, why use type checking at all? Why not change the condition to > use kind_of or simply test result.to_i - result == 0 ? > Well.. Not that it's particularly meaningful, but here's my benchmark for that question: require 'benchamrk' num = 5.5 n = 5_000_000 Benchmark.bmbm do |x| x.report("kind_of?") { n.times do ; n.kind_of? Float ; end } x.report("is_a?") { n.times do ; n.is_a? Float ; end } x.report("to_i") { n.times do ; n.to_i - n == 0 ; end } end Rehearsal -------------------------------------------- kind_of? 1.719000 0.000000 1.719000 ( 1.720000) is_a? 1.641000 0.000000 1.641000 ( 1.642000) to_i 2.750000 0.000000 2.750000 ( 2.751000) ----------------------------------- total: 6.110000sec user system total real kind_of? 1.734000 0.000000 1.734000 ( 1.735000) is_a? 1.703000 0.000000 1.703000 ( 1.720000) to_i 2.688000 0.000000 2.688000 ( 2.689000) __________________ You know how metaprogramming is all about the self, according to Yehuda Katz's latest blog post? :) I, er, forgot to do self.sqrt ... module Math alias_method :old_sqrt, :sqrt def self.sqrt x result = 5.5 #self.old_sqrt(x) if result.is_a? Float "sqrt(#{x})" else result end end end >> puts Math.sqrt(2) => sqrt(2) >> puts Math.methods.find { |i| i[0..0] == "o"} => object_id ... So I'm not sure how to do an alias_method on a method that's got a "self." in front of it, I guess.. puts Math.methods.find { |i| i[0..0] == "o"} -- Posted via http://www.ruby-forum.com/.