Ruby on rails 使用带有yield语句的def内部打印
我试图在函数内部打印。 该函数用于调用块。 但我没有看到函数定义中出现打印。 请解释一下。基本上我不清楚控制流程Ruby on rails 使用带有yield语句的def内部打印,ruby-on-rails,ruby,ruby-block,Ruby On Rails,Ruby,Ruby Block,我试图在函数内部打印。 该函数用于调用块。 但我没有看到函数定义中出现打印。 请解释一下。基本上我不清楚控制流程 def find_all matching_items = [] self.each do |item| if yield(item) puts "after yield" #print not happening matching_items << item end end m
def find_all
matching_items = []
self.each do |item|
if yield(item)
puts "after yield" #print not happening
matching_items << item
end
end
matching_items
end
p ['a', 'b','c','c'].find_all { |item|
if item == 'a'
true
end
}
def find_all
匹配的_项=[]
每个do |项|
如果产量(项目)
放入“产量后”#未打印
匹配项目如果您的代码与编写的代码完全相同,那么您就是在main
上定义和独立的方法find\u all
。键入[1,2,3,4].find_all
时,您正在调用Array
上的find_all
方法,该方法在该方法中定义。因此,您根本没有调用您的方法
你可能想做的是
class Array
def find_all
...
end
end
这样,[1,2,3,4]。find_all将调用此方法
但是,请注意,这可能是一个坏主意:您正在重写一个不属于您的类中的核心方法,因此如果任何其他代码使用find_all方法,这可能会在其他代码中产生您无法预料的后果
您可以尝试定义一个将数组作为参数的方法。您可以将其移动到模块中,但目前:
def find_all(array)
matching_items = []
array.each do |item|
if yield(item)
puts "after yield" #print not happening
matching_items << item
end
end
matching_items
end
def find_all(数组)
匹配的_项=[]
数组。每个do |项|
如果产量(项目)
放入“产量后”#未打印
匹配项目如果您试图重新打开类数组,那么这就是您可以执行的操作
class Array
def find_all(matching_items = [])
self.each do |item|
if yield(item)
puts "after yield" #print not happening
matching_items << item
end
end
matching_items
end
end
p ['a', 'b', 'c', 'c'].find_all { |item|
if item == 'a'
true
end
}
非常感谢您的澄清。我只是为了理解而编码。使用Enumerable就足够了
after yield
["a"]