# Ruby迭代器

#### 迭代器 iterator

• 不同于while循环的用法 ，each 是一个数组的方法，遍历数组中的无数，称之为迭代器iterator
• 其中do….end是each方法的参数 ，称作匿名方法(code block)
``````3.times do
puts "hi"
end``````
##### code block 匿名函数 （无方法名）
``````{puts "hello"} # 大括号的匿名函数  单行

do
puts "Hello"  # 这也是一段匿名函数  多行用do...end
end``````

#### 内部迭代器

``````people = ["Lily" , "Hikari" , "Lucy"]
people.each do |person|
puts person
end

# 反复5次
5.times { puts "Ruby"}

#从一数到九
1.upto(9){ |x| puts x}``````

#### 其它迭代方式

``````# 迭代并返回一个新数组
a = ["a","b","c","d","e"]
b = a.map do |x|
x + "!"
end

puts b.inspect``````
``````# 找出符合条件的值
b = [1,2,3].find_all do |x|
x % 2 == 0
end
puts b.inspect

# 迭代并根据条件删除
a = ["a","b","c"]
a.delete_if do |x|
x >= "b"
end
puts a.inspect``````
``````# 排序
[2,1,3].sort! do |a,b|
b<=>a
end
=begin

a <=> b

=end``````

#### 计算总和 reduce

``````(5..10).reduce do |sum , n|
sum + n
end``````
``````#找出最长字符串
a = ["cat","sheep","bear"]
max = a.reduce do |memo , word|
memo.length > word.length ? memo : word
end
puts max``````

(=￣ω￣=)··· 暂无内容！

17

0

0

0