我现在正在做Ruby Koans练习,并且在以下代码中理解范围如何工作时遇到一些困难:
class AboutScope < Neo::Koan
module Jims
class Dog
def identify
:jims_dog
end
end
end
class String
end
def test_nested_string_is_not_the_same_as_the_system_string
assert_equal false, ::String == "HI".class
end
def test_you_can_get_a_list_of_constants_for_any_class_or_module
assert_equal [:Dog], Jims.constants
end
end
我对上述代码有2个问题:
::String
的类是String?[:Dog]
而不是["Dog"]
?非常感谢!
答案 0 :(得分:2)
AboutScope
的命名空间中。默认情况下,String
会引用AboutScope::String
。要引用根环境中的String
(或Object
中的::
),请附加::String
。有了它,String
引用根Module#constants
。import UIKit
import AVFoundation
class ViewController: UIViewController {
var ButtonAudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("cow", ofType: "wav")!)
var ButtonAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playAudio(sender: AnyObject) {
ButtonAudioPlayer.play();
}
@IBAction func Stop(sender: AnyObject) {
}
按设计,返回其常量名称的数组,表示为符号。它可能被设计为返回一个字符串数组,但是为了表达封闭类的静态事物,符号比字符串更合适。特别是在最近的Ruby之前,每次读取新的字符串文字时都会新创建字符串,而对于同一符号的不同出现,只会创建一次符号。对于可能在代码中多次调用的内容,将它们作为符号而不是字符串更有效。