prc1 = Proc.new do |a, b, c|
p [a, b, c]
end
prc1.call(1, 2) #=> [1, 2, nil]
prc2 = lambda do |a, b, c|
p [a, b, c]
end
prc2.call(1, 2) #=> 错误(ArgumentError)
def power_of(n)
lambda do |x|
return x ** n
end
end
cube = power_of(3)
p cube.call(5) #=> 125
def power_of(n)
Proc.new do |x|
return x ** n
end
end
cube = power_of(3)
p cube.call(5) #=> 错误(LocalJumpError)
def prefix(ary, obj)
result = [] # 初始化结果数组
ary.each do |item| # 逐个检查元素
result << item # 将元素追加到结果数组中
if item == obj # 如果元素与条件一致
return result # 返回结果数组
end
end
return result # 所有元素检查完毕的时候
end
prefix([1, 2, 3, 4, 5], 3) #=> [1, 2, 3]
[:a, :b, :c].collect do |item|
break []
end
square = ->(n){ return n ** 2}
p square[5] #=> 25
def total2(from, to, &block)
result = 0 # 合计值
from.upto(to) do |num| # 处理从 from 到 to 的值
if block # 如果有块的话
result += # 累加经过块处理的值
block.call(num)
else # 如果没有块的话
result += num # 直接累加
end
end
return result # 返回方法的结果
end
p total2(1, 10) # 从 1 到 10 的和 => 55
p total2(1, 10){|num| num ** 2 } # 从 1 到 10 的 2 次冥的和 => 385
def counter
c = 0 # 初始化计数器
Proc.new do # 每调用 1 次 call 方法,计数器加1
c += 1 # 返回加 1 后的 Proc 对象
end
end
# 创建计数器 c1 并计数
c1 = counter
p c1.call #=> 1
p c1.call #=> 2
p c1.call #=> 3
# 创建计数器 c2 并计数
c2 = counter # 创建计数器c2
p c2.call #=> 1
p c2.call #=> 2
# 再次用 c1 计数
p c1.call #=> 4
prc = Proc.new{|a, b| a + b}
p prc.call(1, 2) #=> 3
p prc[3, 4] #=> 7
p prc.yield(5, 6) #=> 11
p prc.(7, 8) #=> 15
p prc === [9, 10] #=> 19
fizz = proc{|n| n % 3 == 0 }
buzz = proc{|n| n % 5 == 0 }
fizzbuzz = proc{|n| n % 3 == 0 && n % 5 == 0}
(1..100).each do |i|
case i
when fizzbuzz then puts "Fizz Buzz"
when fizz then puts "Fizz"
when buzz then puts "Buzz"
else puts i
end
end
prc0 = Proc.new{ nil }
prc1 = Proc.new{|a| a }
prc2 = Proc.new{|a, b| a + b }
prc3 = Proc.new{|a, b, c| a + b +c }
prcn = Proc.new{|*args| args }
p prc0.arity #=> 0
p prc1.arity #=> 1
p prc2.arity #=> 2
p prc3.arity #=> 3
p prcn.arity #=> -1