2017-02-24 47 views
0

爲什麼我無法訪問實例變量?rspec --innit;在.bash_profile中不起作用

let(:hotel2) { Hotel.new name: 'Premier Inn', rating: 1, 
       city: 'Leeds', total_rooms: 15, features: [] } 

我在初始化時調用它,但它一直拋出一個不正確的參數錯誤。

def initialize() 
    @name = name 
    @rating = rating 
    @city = city 
    @total_rooms = total_rooms 
    @features = features 
    end 

任何想法?

回答

0

您的初始化簽名與您的呼叫簽名不匹配。你正在傳遞一個散列,但沒有收到散列。有很多方法可以定義參數列表來完成這項工作。這裏是一個:

class Hotel 
    def initialize(hash) 
    @name = hash[:name] 
    @rating = hash[:rating] 
    @city = hash[:city] 
    @total_rooms = hash[:total_rooms] 
    @features = hash[:features] 
    end 
end 

This blog post概述瞭如何使用Ruby V2關鍵字參數。這將是另一種或許更好的方式來定義你的initialization。下面是一個例子:

class Hotel 
    def initialize(name: , rating:, city:, total_rooms:, features:) 
    @name = name 
    @rating = rating 
    @city = city 
    @total_rooms = total_rooms 
    @features = features 
    end 
end 

您可以設置關鍵字參數的默認值,並使其成爲必需的。在這個例子中,它們都是強制性的。