简体   繁体   English

多行与内联块之间的不同行为

[英]Different behavior between multi-line vs. in-line block

I am curious why these are producing different outputs.我很好奇为什么这些会产生不同的输出。 The desired output is an array of ActiveRecord records.所需的 output 是一个包含 ActiveRecord 条记录的数组。

When using an in-line block, it appears to be doing the ActiveRecord lookup, but subsequently nests the original array (minus the reject ed elements) inside of another array and appends the nested arrays to the variable.使用内联块时,它似乎在进行 ActiveRecord 查找,但随后将原始数组(减去reject ed 元素)嵌套在另一个数组内,并将嵌套的 arrays 附加到变量。

When using a multi-line block, the expected behavior occurs, ie the ActiveRecord lookup occurs and the identified records are appended to the variable.使用多行块时,会发生预期的行为,即发生 ActiveRecord 查找,并将识别的记录附加到变量。

x = []
y = ["", "1353", "1155"]
x << y.reject!(&:empty?).each { |i| User.find(i) }
# => ["1353", "1155"]
x
#=> [["1353", "1155"]]

vs对比

x = []
y = ["", "1353", "1155"]
y.reject!(&:empty?)
y.each do |i|
  x << User.find(i)  
end  
# => ["1353", "1155"]
x
#=> [#<User:0x00007fc7fbacc928
#  id: 1353,
#  login: nil,
...

The difference is that.each returns the array itself, so不同之处在于.each 返回数组本身,所以

[1,2,3].each { nil }
# [1,2,3]

so you are appending the rejected Y numbers in X, and your.each is being useless on the first example (that's also why it is an array of array, because '<<' inserts the element array inside your array, and not all the individual elements)所以你在 X 中附加被拒绝的 Y 数字,而你的.each 在第一个例子中是无用的(这也是为什么它是一个数组的数组,因为'<<'将元素数组插入你的数组中,而不是所有的个别元素)


In your second example, your 'each' is in fact appending the elements to your array inside the block, so no "return" dependency.在您的第二个示例中,您的“每个”实际上是将元素附加到块内的数组中,因此没有“返回”依赖性。 If you want to do it on single line, you would have to do如果你想在单行上做,你必须做

y.reject(&:empty?).each { |i| x << User.find(i) }

so it would do the calculation inside de block and if you want each loop to return the value inside the block you should use 'map' instead of 'each', and the 'concat' or '+' to sum the arrays (so it sums or concats each individual elements), so所以它会在de块内进行计算,如果你想让每个循环返回块内的值,你应该使用'map'而不是'each','concat'或'+'来总结arrays(所以它求和或连接每个单独的元素),所以

x.concat(y.reject(&:empty?).map{ |i| User.find(i) })

OBS: As @tadman suggested on comment, I also removed the "bangs" for reject, as the 'reject,' method does not expect to always return all the values, check his comment for more information OBS:正如@tadman 在评论中建议的那样,我还删除了拒绝的“刘海”,因为“拒绝”方法并不期望总是返回所有值,请查看他的评论以获取更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM