2012-01-05 29 views
0

我正在讀一本關於Ruby/Rails的書,並對簡單的東西有疑問。在下面的「轉向」方法中,作者使用「自我」,它指的是類。但是,有什麼區別(在你可以和不能做什麼而言),如果有的話,如果他離開的「自我」,只是做了此代碼中類變量的用途

direction = new_direction 

代碼

class Car << ActiveRecord::Base 

    validates :direction, :presence => true 
    validates :speed, :presence => true 

    def turn(new_direction) 

    self.direction = new_direction 

    end 

end 
+0

我notnsure爲什麼其他的答案被忽略了AR方面,但是從你的那些外賣應該是類的方法必須被調用,以堅持價值。這是Rails代碼中常見的錯誤,我在評論中指出它,所以它不會丟失。 – 2012-01-05 02:38:40

+0

另外,請注意@direction又是不同的,並且也不會被保留。 – 2012-01-05 03:04:51

+0

所有這些答案對我有點幫助,不知道該給誰支票。 – Leahcim 2012-01-05 03:35:16

回答

1

ActiveRecord(堅持)由於AR的實施,必須使用self訪問變量。

這裏,self將列(DB)變量與「正常」,未保留的實例屬性區分開來。區別在於該值不會在保存或更新時保存在數據庫中。

3

一些背景:紅寶石中「自我」的存在只意味着當前的對象。您會看到類似這樣的類方法,其中方法是在Class上定義的,而不是實例。

class Cookbook 
    def self.find_recipe 
    end 
    def is_awesome? 
    true 
    end 
end 

find_recipe是食譜的方法,讓你通過Cookbook.find_recipe調用它,你會通過調用is_awesome上的一個實例:

cookbook = Cookbook.new 
puts cookbook.is_awesome? 

所以:原因self.direction=被稱爲是作者不想要在方法中創建一個名爲direction的變量。如果作者有:

class Car 
    attr_accessor :direction 
    def turn(new_direction) 
    direction = new_direction 
    end 
end 

那麼你會看到:

car = Car.new 
car.direction = :left 
car.turn(:right) 
car.direction 
=> :left  

將其更改爲self.direction,然後將它正確設置實例的變量。

2

這將設置一個局部變量a到的b

a = b 

值但是,這是不同的:

self.a = b 

這實際運行a=方法與b作爲參數。這實際上意味着:

self.a=(b) 

最後,雖然方法可以self被稱爲與提供self作爲接收器,同樣是真正的分配。 a = b將永遠不會調用a=方法,並且只會分配一個局部變量。

1

在這裏看到:http://snippets.dzone.com/posts/show/7963

self.direction = new_direction 

分配一個新值「方向」上車的實例屬性,而

direction = new_direction 

創建一個名爲「方向」,並返回一個局部變量它的值但不更新Car實例。

因此,舉例來說,我相信下面應該發生:

class Car << ActiveRecord::Base 

    validates :direction, :presence => true 
    validates :speed, :presence => true 

    def turn(new_direction) 
    self.direction = new_direction 
    end 

    def set_speed(new_speed) 
    speed = new_speed 
    end 
end 

alf = Car.new 

alf.direction = "North" 
alf.speed = 1 

alf.turn = "South" 
alf.set_speed = 5 

> alf.direction 
=> "South" 

> alf.speed 
=> 1 
+0

好吧,所以「5」的速度不會持續,因爲它沒有設置爲類變量,但然後爲什麼「alf.speed」最後返回「1」。如果最初使用普通變量設置「1」,它會持續多久?你能解釋一下嗎? – Leahcim 2012-01-05 03:34:49

+0

@Michael這裏沒有持久性,這是一個演示set_speed *如何不*設置持久列字段「速度」。如果保存AR記錄或更新其屬性,持久性僅用於播放。看看最後alf.speed是「1」嗎?這是因爲set_speed設置了本地「速度」,而不是實例變量或列變量。 – 2012-01-05 03:39:31

+0

@DaveNewton感謝我瞭解到,如果set_speed只設置一個本地速度,那麼alf.speed = 1也是一個本地「速度」? – Leahcim 2012-01-05 03:46:16

相關問題