本文介绍了如何从 ruby​​ 外部访问类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从类外的方法访问类变量.

I'm trying to access a class variable from a method outside of the class.

这是我的课:

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

这是试图访问类变量@@bookCount 的方法

This is the method trying to access the class variable @@bookCount

def seeBookShelf
  if @@bookCount == 0
    puts "Your bookshelf is empty."
  else
    puts "You have " + @bookCount + " books in your bookshelf:"
    puts allBooks
  end
end

当我尝试执行该方法时,我得到了这个:

When I try to execute the method I get this:

undefined local variable or method `bookCount' for main:Object (NameError)

如何从外部访问 bookCount?

How can I access bookCount from the outside?

推荐答案

使用 class_variable_get 访问类外的类变量:

Use class_variable_get to access a class variable outside of a class:

class Foo
  @@a = 1
end

Foo.class_variable_get(:@@a)
=> 1

这篇关于如何从 ruby​​ 外部访问类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:29