我正在实现一个包含一个集合的硬编码下拉列表的表单,我想知道什么是最好的解决方案,我知道两种方式暴露在工作之下,我仍然做如下:
class Example
# Options for Example.
self.options
[ 'Yes', 'No', 'Not sure' ]
end
end
Run Code Online (Sandbox Code Playgroud)
这被称为Example.options,但我知道也可以这样做:
class Example
# Options for Example.
OPTIONS = [ 'Yes', 'No', 'Not sure' ]
end
Run Code Online (Sandbox Code Playgroud)
这将被称为Example::OPTIONS.
问题是,这些中的任何一种都是好方法还是根本不重要?
我在本教程中遇到了以下示例:
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
Run Code Online (Sandbox Code Playgroud)
@@只能在Song课程中礼貌地播放吗?这篇评论提出了不建议使用类变量的观点.是不是b/c它们在日常使用中通常不需要,并且在使用时会产生很多调试问题?