Ruby define_method def 的区别
今天稍微搜了一下很少有讲define_method跟def的中文文章,英文的也没有讲得很明白的,今天就斗胆把我的理解跟大家分享一下。
入门级别:
class Foodef initialize x@x = xendendclass Bardefine_method :initialize do |x|@x = xendend
require 'benchmark'Foo = Class.newBar = Class.newt = 100000Benchmark.bm do |x|x.report('def') {t.times {Foo.class_eval {def a;end}}}x.report('define_method') {t.times {Bar.class_eval {define_method(:a){}}}}end
method_name = ''puts 'Type "exit" to exit...'class SmartClassdef self.method_added method_nameputs "New Method: #{method_name.chomp} has been created."endendwhile method_name.chomp != 'exit'method_name = getsSmartClass.class_eval dodefine_method(method_name) {}endend
class ShabbyClassmy_name = 'piecehealth'def say_my_nameputs my_nameendendclass SmartClassmy_name = 'piecehealth'define_method :say_my_name doputs my_nameendendSmartClass.new.say_my_name# piecehealthShabbyClass.new.say_my_name# NameError
class Companyattr_accessor :service_teldef initialize name, service_tel @name = name@service_tel = service_telenddef release_new_product product_nameproduct = Object.const_set(product_name.capitalize, Class.new)company = selfproduct.class_eval dodefine_method :initialize do@name = product_name@company = companyendattr_reader :companyendendendapple = Company.new('Apple', '123-1234567')apple.release_new_product('iPhone32z')ip32z = Iphone32z.newp ip32z # #<Iphone32z:0x25d2d70 @name="iPhone32z", @company=#<Company:0x25d3028 @name="Apple", @service_tel="123-1234567">>p ip32z.company.service_tel # "123-1234567"apple.service_tel = '321-7654321'p ip32z.company.service_tel # "321-7654321"