Ruby学习笔记
学了一段时间的Ruby,长久未使用,日渐模糊,重新来过,留作笔记。
数组和散列表 (Arrays and Hashs)
Ruby的数组(arrays)和散列表(hashs)是被索引的收集(indexed collections)。其它编程语言散列表叫做哈希或者键值数组。 散列表支持任何对象作为它的键。
创建数组(Array),方括号包裹逗号分隔的字符串,数组索引从0开始。
fruit = ['apple', 'orange', 'banana', 'melon'] 快捷方式 fruit = %w(apple orange banana melon) // 注意空格 fruit.class # Array
创建散列表(Hash),花括号包裹,键和值之间用=>分隔。
my = {
"name" => "david",
"sex" => "male",
"age" => 23
}
my.class # Hash
访问数组或散列表,只需提供相应的索引即可。访问不存在的索引会返回nil,类似于其它语言中的null。
fruit[0] # apple my['name'] # david fruit[4] # nil my['qq'] # nil
现在还没有评论