Back

[教程] web + rails 入门 2 (大师原创) ruby 10分钟入门

发布时间: 2015-06-04 07:59:00

ruby 的基础:

声明个class: 

class Apple
  @color = ''
  def color
     return @color
  end 
  def color= (new_color)
    @color = new_color
  end

  # 以上代码可以简写为: attr_accessible :color
  @@name = 'apple'
  private 
  def my_private_method
  end 
end

上面代码中,   @color 是 instance variable,  @@name 是class variable.  (所有的instance 的 @@name 都相同, @color 都不同 )

my_private_method 是私有方法。

ruby中的简写。

每个函数的最后一行默认是返回值,是不需要写return的,例如:

def color
  'red'
end

方法调用的最外面的大括号可以省略。例如:

puts "hihihi"   # 等同于   puts("hihihi")

hash最外面的{} 在大多数情况下可以省略,例如:

Apple.create :name => 'apple', :color => 'red'
等同于: Apple.create({:name => 'apple', :color => 'red'})
等同于: Apple.create name: 'apple', color: 'red'

调用某个block中的某个方法:

Apple.all.each do {  |apple|      apple.name  }
等同于:   
Apple.all.map(&:name)

self 

在普通的ruby class中,self 等同于 这个class.   例如:

class Apple
    def self.color   # 等同于:  def Apple.color
    end
end

在 ActiveRecord中, self 很多时候指带某个instance ,例如:

class Apple  < ActiveRecord::Base
    before_save
        self.name = 'new_name'   # 这里的self 指 当前正在被保存的 apple instance. 
    end
end

Back