class Restaurant
attr_accessor :average_rating, :city
def initialize(city, name)
@city = city
@name = name
@number_of_ratings = 0
@sum_of_ratings = 0
end
def rate(new_rate)
@number_of_ratings = 1
@sum_of_ratings = new_rate
@average_rating = @sum_of_ratings.to_f / @number_of_ratings
end
def self.filter_by_city(restaurants, city)
restaurants.select { |restaurant| restaurant.city == city }
end
end
上面的代碼是挑戰的一部分,我一直未能通過#filter_by_city 方法的測驗。我檢查了解決方案,唯一的區別是self.方法名稱之前。我試圖理解究竟self是什么,但如果沒有背景關系就很難理解。在這個特定的類方法中,究竟在self做什么?我知道該方法的主體在做什么,即按城市過濾餐館,但它是如何運行的呢?
uj5u.com熱心網友回復:
self是類Restaurant。def self.method是如何在類本身而不是類的實體上實作方法。Restaurant.filter_by_city(...)而不是Restaurant.new.filter_by_city(...).
selfRuby 中的變化取決于背景關系。在方法中,self是呼叫該方法的物件。
在class Restaurant塊內,在任何方法之外,self是Restaurant一個類物件的物件。在 Ruby 中,一切都是物件。一切。
你也可以通過宣告一個類是實體的塊來做到這一點。
class << self
def filter_by_city(restaurants, city)
restaurants.select { |restaurant| restaurant.city == city }
end
end
如果你有很多類方法,通常你會使用這種語法。
有關更多資訊,請參閱Ruby 中的自我:全面概述。
uj5u.com熱心網友回復:
在 ruby?? 中定義方法時,您可以選擇使用def <receiver>.<method>語法而不是普通的方法顯式定義該方法的接收器def <method>
object = Object.new
def object.foo
:foo
end
object.foo #=> foo
接收者必須是單數參考或運算式(但必須用括號括起來):
a = [Object.new, Object.new]
def (a.first).foo
:foo
end
def (a[1]).bar
:bar
end
a[0].foo #=> :foo
a.last.bar #=> :bar
a.first.bar #=> undefined method
定義接收者時,直接在接收者的單例類上定義方法,忽略定義方法的背景關系:
class A
o = Obejct.new
def o.foo
end
end
A.new.foo #=> undefined method
即使方法 foo 是在類 A 主體中定義的,但由于顯式接收器,它對其實體不可用
self是回傳當前“背景關系”的 ruby?? 關鍵字。在方法內部,self(通常)是呼叫的接收者,并且在模塊內部self回傳該模塊。所以:
module Wrapper
module SomeModule
puts self.name
end
end
將列印Wrapper::SomeModule。
這意味著:
class A
def self.foo
end
end
與以下內容完全相同:
class A
def A.foo
end
end
因此,該方法直接定義在類上A,并且只能在類上直接呼叫A.foo,而不是在其實體上。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/453758.html
