最近的Ruby for Rails读书笔记

1, 用"class <<"定义class method
class User < ActiveRecord::Base

class << self
  def authenticate(username, password)
    find_by_username(username, :conditions => [password_hash = ?", Digest::SHA1.hexdigest(passwword)])
  end


2, 用self.included(class)方法作为include模块的hooks
module M
  def self.included(c)
    puts "I have just been mixed into #{c}."
  end
end

class C
  include M
end


3, 用self.inherited(subclass)作为class继承的hooks
class C
  def self.inherited(subclass)
    puts "#{self} just got subclassed by #{subclass}"
  end
end

class D < C
end

用self.const_missing(const)作为class缺失const的hooks
class C
  def self.const_missing(const)
    puts "#{const} is undefined-setting it to 1."
    const_set(const, 1)
  end
end

puts C::A


4, 用eval/instance_eval/class_eval(module_eval)动态执行程序
str = "hello"
eval "str + ' Fred'"


5, 用Proc定义代码块
pr = Proc.new { |x| puts "Called with argument #{x}" }


6, 用lambda定义匿名方法
lam = lambda { puts "A lambda!" }
lam.call

你可能感兴趣的:(C++,c,读书,Ruby,Rails)