Ruby如何遍历实例数组?Order实例数组遍历遇问题求助
Hey there, let's break down what might be going wrong with your code. You mentioned that Order.all.first[:time] works fine, but when you loop through all orders and try to process e[:time] into an array plus a bitwise operation (b &...), you're hitting issues. Here are the most common pitfalls and fixes to check:
1. Watch out for nil time values
Just because the first order has a valid time string doesn't mean all orders do. If any record has a nil time, Array(nil) will spit out an empty array []—which can throw off your subsequent & (intersection) operation, leading to unexpected results or errors.
Add a quick check to skip records without a time value:
a = [] Order.all.each do |e| next if e[:time].nil? # Or use `.blank?` if you also want to skip empty strings b = Array(e[:time]) # Continue with your b & ... logic here # Example: if you're intersecting with another array called valid_chars # common = b & valid_chars # a << common end
2. Are you accidentally splitting into individual characters?
When you call Array(e[:time]) on a string like "01.00", it converts each character into an array element: ["0", "1", ".", "0", "0"]. If your goal was to split the time into hours and minutes instead, use split('.') instead—it'll give you a much more useful array:
b = e[:time].split('.') # Result: ["01", "00"] for "01.00"
This is way better if you need to work with hours or minutes separately.
3. Optimize with pluck instead of loading full instances
Loading every single Order instance just to get the time attribute is overkill. Use pluck to fetch only the time values directly from the database—it's faster and uses way less memory:
a = [] Order.pluck(:time).compact.each do |time_str| b = Array(time_str) # Or split('.') as needed # Your b & ... operation here end
The compact removes any nil values upfront, so you don't have to check inside the loop.
4. Double-check your intersection logic
If you're using & to find common elements between b and another array, make sure the comparison array is structured the same way as b. For example:
- If
bis individual characters (["0","1",...]), your comparison array should be something like%w(0 1 2 3 4 5 6 7 8 9 .)to match valid time characters. - If
bis split into hours/minutes (["01","00"]), your comparison array might be a list of valid hour strings like%w(00 01 ... 23).
If you can share the full code for the b &... part, I can give you a more specific fix!
内容的提问来源于stack exchange,提问作者Johan Faerch

