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

问题描述

我从 本教程:

class Song
  @@plays = 0

  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
    @plays = 0
  end

  def play
    @plays += 1
    @@plays += 1
    "This song: #@plays plays. Total #@@plays plays."
  end
end

s1 = Song.new("Song1", "Artist1", 234)    # test songs
s2 = Song.new("Song2", "Artist2", 345)

puts s1.play
puts s2.play
puts s1.play
puts s1.play

@@plays 是否只能在 Song 班级内礼貌地访问?这篇评论 提出了不建议使用 class 的观点变量.是不是 b/c 在日常使用中通常不需要它们,并且在使用时会产生很多调试问题?

Is @@plays politely accessible only inside the class Song? This commentary brings up the point of not recommending the use of class variables. Is it b/c they are often not required in common-day use, and create a lot of debugging headaches when used?

推荐答案

@@ 变量将成为一个类变量.这通常是不好的做法.在您的代码中它是多余的,因为@plays == @@plays(除非您在代码中的其他地方设置@@plays(不好的做法))

The @@ variable will a class variable. This is generally bad practice. In your code its redundant because @plays == @@plays (unless you set @@plays elsewhere in your code (bad practice))

事实上,现在我看它,它们并不完全相同.@plays 会记录一首歌曲的播放次数,@@plays 会记录所有歌曲的播放次数.尽管如此,使用@@plays 可能是不好的做法.通常,你会有一个像Player"这样的父类来管理所有的歌曲.在Player"类中应该有一个名为@total_plays 的实例变量.

Actually now that I look at it, they aren't really the same. @plays keeps a count of how many times an individual song has been played, and @@plays will keep a count of all songs. Still, its likely bad practice to use @@plays. Usually, you'd have a parent class like "Player" that is managing all the songs. There should be an instance variable called @total_plays in the "Player" class.

这篇关于Ruby 中的类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:35