我正在尝试从类外部的方法访问类变量.
这是我的班级:
class Book
@@bookCount = 0
@@allBooks = []
def self.allBooks
@@allBooks
end
def self.bookCount
@@bookCount
end
attr_accessor :name,:author,:date,:genre,:rating
def initialize(name, author, date, genre, rating)
@name = name
@author = author
@date = date
@genre = genre
@rating = rating
@@bookCount += 1
@@allBooks << self
end
end
Run Code Online (Sandbox Code Playgroud)
这是尝试访问类变量@@ bookCount的方法
def seeBookShelf
if @@bookCount == 0
puts "Your bookshelf is empty."
else
puts "You have " + @bookCount + " books in your bookshelf:"
puts allBooks
end
end
Run Code Online (Sandbox Code Playgroud)
当我尝试执行该方法时,我得到了这个: …