zip
兩個集合同步遍歷 zip 主要場景是 你有兩個集合并且向同步進行遍歷,每次迭代保持下標的一致。方法接受兩個參數 一個是 要同步遍歷的若干個數組,另一個是迭代的代碼塊。
[*1..3].zip([*4..6]).map { |a, b| a + b }
# => [5, 7, 9]
如果不傳入block的話
[*1..3].zip([*4..6])
# => [[1, 4], [2, 5], [3, 6]]
each.with_index(n)
遍歷并且攜帶指定初始值的下標,這樣就可以在循環能使用指定的下標序列
%w(a b c).each.with_index(1).map { |w, i| [w, i] }
# => [["a", 1], ["b", 2], ["c", 3]]
each_with_object
這是方法是非常好用的,它可以將參數作為,迭代block的最后一個參數,并且在下一個迭代中將上一個傳入,知道最后返回。
我們來看個例子,假設有兩個集合,想要一個做為哈希的key,另一個想做為對應的值之前的做法是這樣的
map = {}
keys = %w(name age sex)
values = ['Tom', 33, 'male']
keys.zip(values).each do |item|
map[item.first.to_sym] = item.second
end
# map => {"name"=>"Tom", "age"=>33, "sex"=>"male"}
使用each_with_object之后,這樣代碼更加貼近函數式編程的風格
keys = %w(name age sex)
values = ['Tom', 33, 'male']
result = keys.zip(values).each_with_object({}) do |item, map|
map[item.first.to_sym] = item.second
end
# result => {"name"=>"Tom", "age"=>33, "sex"=>"male"}
all?
判斷集合中的所有元素,如果集合中的所有元素,都符合,指定的block 條件的話,返回true 否則False
[*1..100].all?(&:positive?)
# => true
any?
如果集合中任意元素,滿足給的block條件的話,返回true 否則false
[*-10..10].any?(&:positive?)
# => true
product
笛卡爾乘積
[*1..3].product([*4..6])
# => [[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]]
再舉一個實際的例子,在多對多數據表關聯中會有這樣的ER圖
多對多
現在已知你有一組 post_ids 和 reader_ids 想要創建關聯關系,那么可以使用笛卡爾乘積
ids = post_ids.product(reader_ids)
Readered.import [:post_id, :reader_id], ids
each_slice
將集合切割成,并且遍歷,切割力度要根據給定的常數
# 輸出5X5陣列
[*1..25].each_slice(5).each { |i| puts i * ' ' }
# 1 2 3 4 5
# 6 7 8 9 10
# 11 12 13 14 15
# 16 17 18 19 20
# 21 22 23 24 25
select
篩選出集合中滿足條件的子集合, 下面是找出集合中的整數。
numbers = [2.2, 1, 14.5, 99.3, 55, 12.2]
numbers.select(&:integer?)
# => [1, 55]
detect
篩選出集合中滿足條件的第一個元素。
numbers = [2.2, 1, 14.5, 99.3, 55, 12.2]
numbers.select(&:integer?)
# => 1
none?
使用none? 可以判斷 一個集合中,是否所以元素都不滿足給定的 block 條件
[true, false, false].none?
# => false
[1.1, 2.2 , 3.3].none?(&:integer?)
# => true
one?
使用one 可以判斷一個集合中,是否有且只有一個元素滿足給定的 block 條件
[true, false, false].one?
# => true
[true, false, false, true].one?
# => false