2011-10-05 162 views
3

在Ruby Koans中,您必須填寫下面代表string[1]的空白。爲什麼答案是97?爲什麼這個字符串值是一個數字?

def test_you_can_get_a_single_character_from_a_string 
    string = "Bacon, lettuce and tomato" 
    assert_equal ___ , string[1] 
end 
+1

你從哪裏得到koan?該公司在[三月]發生了變化(https://github.com/edgecase/ruby_koans/commit/a46642e192844a312c344d43147a81ecf43f438b)。 –

+1

你期待着答案是什麼? –

+0

安德魯,http://koans.heroku.com – Simpleton

回答

7

97是'a'的ASCII碼十進制表示,它是位於字符串[1]的字母。

+4

而在Ruby 1.9中,'string [1]'的結果是''a「'。 – molf

+1

燁,Ruby 1.9中這個公案不再正確: '$ IRB 1.9.2p290:001>字符串= 「AAAAA」 => 「AAAAA」 1.9.2p290:002>串[1] => 「一」' 紅寶石1.8: '$ IRB >>字符串= 「AAAAA」 => 「AAAAA」 >>串[1] => 97' – stantonk

2

97是小寫字母a的ASCII值(十進制)。

2

string[1]會給你字符串的第二個字符,第一個字符爲0.這被轉換爲一個整數,在ASCII中被表示爲97。所以這給你97.

相關問題