我如何将下面的条件提取到方法中?
我既要为变量设置一个新值,又要返回迭代项的值。
my_variable = 0
collection_one.each do |item|
if item.some_attribute != my_variable
my_variable = item.some_attribute
item.some_attribute
end
# do other stuff
end
collection_two.each do |item|
if item.some_attribute != my_variable
my_variable = item.some_attribute
item.some_attribute
end
# do other stuff
end
的值my_variable
将不会在下一次迭代中持续存在,因为它会在第一个each
方法中被覆盖。为此,您可以执行以下操作:
my_variable = 0
collection_one.each_wth_object do |item, obj|
if item.some_attribute != my_variable
obj << [item.some_attribute, my_variable]
my_variable = item.some_attribute
item.some_attribute
end
# do other stuff
end
my_variable = 0 # define it again
collection_two.each_with_object([]) do |item, obj|
if item.some_attribute != my_variable
obj << [item.some_attribute, my_variable]
my_variable = item.some_attribute
item.some_attribute
end
# do other stuff
end
这里obj
将举行不同的阵列排列的值:[[item.some_attribute, my_variable], [...], [..],..]
内的每个each_with_object
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句