2017-02-24 4 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

初期化シグネチャが発信シグネチャと一致しません。あなたはハッシュを渡していますが、ハッシュを受け取っていません。この作業を行うために引数リストを定義する方法はいくつかあります。ここでは1です:

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を定義するもう1つ、おそらくより良い方法でしょう。これはその例です:

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

キーワード引数のデフォルトを設定し、必須にすることができます。この例では、すべて必須です。

関連する問題