trio = Proc.new do |x|
tf = true
puts x
if tf
puts "ai yo"
end
end
trio.call([1, 2, 3, 4, 5])
输出:
1 2 3 4 5 ai yo #它只做一次ai yo部分,当我认为它应该在每个数字之后做的时候
但我对输出的期望是:
1 ai 2 ai 3 ai 4 ai 5 ai
我仍然不明白为什么会发生这样的事情。
我正在尝试让这个程序工作,我认为这将是一个很酷的使用procs的方式,尽管在这个特定的问题中,我基本上不需要:
#The prime factors of 13195 are 5, 7, 13 and 29.
#What is the largest prime factor of the number 600851475143 ?
number = 13195
def factorsAndOptions(num, proc = Proc.new {|x|return x})
factorsArray = []
for i in 1..num
factorsArray.push(i) if num % i == 0
end
proc.call(factorsArray)
end
largestPrime = Proc.new do |x|
prime = true
for j in 2...x
if (x % x == 0)
prime = false
end
end
larger = x if prime && larger > x
puts larger
larger
end
factorsAndOptions(number, largestPrime)
发布于 2018-08-07 02:36:19
call
不会遍历参数。你写的是,有效的:
puts [1, 2, 3, 4, 5]
puts "ai yo"
如果要进行迭代,请使用each
[1, 2, 3, 4, 5].each(&trio)
或者:
[1, 2, 3, 4, 5].each { |i| trio.call(i) }
发布于 2018-08-07 16:36:58
如前所述,您没有任何循环块。您的proc - trio
将整个数组作为单个元素进行操作。
在您的示例中:x
成为[1, 2, 3, 4, 5]
,而不是您所期望的数组的单个元素。
要避免这种情况,您可以在Proc中循环,或者创建一个单独的Proc,该Proc将遍历数组的元素并调用第一个Proc。
示例1
trio = Proc.new do |arr|
arr.each do |elem|
puts elem
if tf
puts "ai yo"
end
end
end
这里假设arr
是一个数组
示例2
trio = Proc.new do |x|
tf = true
puts x
if tf
puts "ai yo"
end
end
trio_helper = Proc.new do |x|
arr = x.to_a
arr.each do |elem|
trio.call(elem)
end
end
trio_helper.call([1, 2, 3, 4, 5])
这利用了您编写的原始Proc,并使用另一个Proc迭代数组,并在每个元素上调用第一个Proc。
https://stackoverflow.com/questions/51713677
复制相似问题