Ruby类函数定义的几种方式
Ruby类函数定义的几种方式
参考:ruby-defining-class-methods
1、
class Person def Person.find(id) ... endend
class Person def self.find(id) ... endend
class Person class << self protected def find(id) ... end endend
class Object # http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html def meta_def name, &blk (class << self; self; end).instance_eval { define_method name, &blk } endendclass Service def self.responses(hash) hash.each do |method_name, result| meta_def method_name do result end end end responses :success => 20, :unreachable => 23endService.success # => 20Service.unreachable # => 23
class Person instance_eval do def find(id) ... end endend