'array.map' 是否保留原始顺序? [英] Does 'array.map' preserve the original order?

查看:50
本文介绍了'array.map' 是否保留原始顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 User 类,它是 has_many Jobs.我使用以下代码映射作业:

I have a User class that has_many Jobs. I map jobs with the following code:

def ranges
  user.jobs.map { |u| [u.start_at, u.end_at] }
end

我有一个比较两个数组的规范:

I have a spec that compares two arrays:

my_array = [[start1, end1], [start2, end2]]
expect(ranges).to eq my_array

它在本地传递,但不在 Bamboo 构建中传递.我不得不改变它以通过构建.我仍然不明白为什么它会这样.即使地图不保留顺序,我也希望有一些随机模式.

It passes on local, but not on Bamboo build. I had to change it to pass the build. I still don't understand why it behaves like this. I expect some random pattern even if map doesn't preserve the order.

为什么这会通过我的本地,但在 Bamboo 构建中失败?

Why does this pass on my local, but fails in Bamboo build?

推荐答案

根本问题不是因为 map,它应该保留顺序.相反,user.jobs 本身可能采用不同的顺序(在每个测试中),因为没有使用任何明确的 order by 子句.如果没有明确的order by,即使您按特定顺序创建作业,也无法保证作业的顺序.

The underlying issue isn't because of map, which should preserve the order. Rather, user.jobs itself may be in a different order (in each test) since there isn't any explicit order by clause used. Without an explicit order by, you can't guarantee the order of the jobs even if you create them in a specific order.

你应该使用 http://www.rubydoc.info/github/rspec/rspec-expectations/RSpec/Matchers:match_array 而不是 eq 进行比较以避免此类问题.

You should use http://www.rubydoc.info/github/rspec/rspec-expectations/RSpec/Matchers:match_array instead of eq for comparison to avoid such issues.

这篇关于'array.map' 是否保留原始顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆