在 Ruby 中,数组是有序的、以整数为下标的集合,可以存放任意对象。
数组下标从0开始。
负下标相对于数组末尾计数,例如下标-1表示数组的最后一个元素,-2表示倒数第二个元素,以此类推。
数组通常使用[]表示法创建。
数组可以包含各种不同类型的对象。
array = [1, "two", 3.0]
数组中的元素可以通过下标用#[]方法获取。
它会返回该下标处的元素,或者返回一个子数组:从起始下标开始,持续指定的长度。
负下标从数组末尾向前计数。
a = [ "a", "b", "c", "d", "e" ]
a[2] #=> "c"
a[6] #=> nil
a[1, 3] #=> [ "b", "c", "d" ]
a[-1] #=> "e"
a[-2] #=> "d"
a[-3, 2] #=> ["c", "d"]
数组上有很多好用的辅助方法。 以下是一些比较常见的:
fibonacci = [0, 1, 1, 2, 3, 5, 8, 13]
fibonacci.size #=> 8
fibonacci.sum #=> 33
fibonacci.reverse #=> [13, 8, 5, 3, 2, 1, 1, 0]
在 Ruby 中,我们不用循环来遍历集合,而是使用枚举。
枚举是指遍历一个集合(这里是数组),并对其中每个对象执行某种操作。枚举是 Ruby 中的核心概念,排序、分组、映射、归约等操作都要用到它。
一个打印数组中每个单词的枚举如下所示:
words = ["the", "cat", "sat"]
words.each do |word|
puts word
end
# Output:
# the
# cat
# sat
在这个例子中,我们在数组上调用了.each方法,并传入一个_块_,它接收一个形参(word)并把它打印出来。
在后续的学习中,我们会更深入地学习_块_,现在你可以把它们看作可以接收零个或多个实参的匿名函数。
它们可以用do...end语法(如上)或{}语法(如下)来定义。
下面是另外一些使用块的数组方法示例:
fibonacci = [0, 1, 1, 2, 3, 5, 8, 13]
fibonacci.count { |number| number == 1 } #=> 2
fibonacci.any? { |number| number == 6 } #=> false
fibonacci.select { |number| number.odd? } #=> [1, 1, 3, 5, 13]
fibonacci.all? { |number| number < 20 } #=> true
fibonacci.map { |number| number * 2 } #=> [0, 2, 2, 4, 6, 10, 16, 26]
你是一位热衷于观鸟的人,会记录过去 7 天里有多少只鸟来到你的花园。
你有 5 个任务,都与你花园里来访鸟类的数量有关。
为了便于比较,你总是在手边保留一份上周计数的副本,它们是:0、2、5、3、7、8 和 4。实现BirdCount.last_week方法,返回上周的计数:
BirdCount.last_week
# => [0, 2, 5, 3, 7, 8, 4]
实现BirdCount#yesterday方法,返回昨天有多少只鸟来到你的花园。这些鸟类计数按天排序,第一个元素是最早那天的计数,最后一个元素是今天的计数。
birds_per_day = [2, 5, 0, 7, 4, 1]
bird_count = BirdCount.new(birds_per_day)
bird_count.yesterday
# => 4
实现BirdCount#total方法,返回来过你花园的鸟的总数:
birds_per_day = [2, 5, 0, 7, 4, 1]
bird_count = BirdCount.new(birds_per_day)
bird_count.total
# => 19
有些日子比其他日子更忙。忙碌的一天是指有 5 只或更多鸟来到你花园的日子。
实现BirdCount#busy_days方法,返回忙碌的天数:
birds_per_day = [2, 5, 0, 7, 4, 1]
bird_count = BirdCount.new(birds_per_day)
bird_count.busy_days
# => 2
实现BirdCount#day_without_birds?方法,如果有一天没有鸟来访花园,就返回true;否则返回false:
birds_per_day = [2, 5, 0, 7, 4, 1]
bird_count = BirdCount.new(birds_per_day)
bird_count.day_without_birds?
# => true