为什么这个字符串值是一个数字?

为什么这个字符串值是一个数字?

问题描述:

在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

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

97是小写字母a的ASCII值(十进制)。

string[1]会给你字符串的第二个字符,第一个字符为0.这被转换为一个整数,在ASCII中被表示为97。所以这给你97.