如何拆分Ruby哈希数组?.split无效且需保持元素顺序
Got it, so you need to split your array of hashes into two ordered chunks without relying on condition-based methods like partition or select, and split isn't working for you. Here's how to do it cleanly while preserving the original element order:
Method 1: Use first and drop
If you know exactly how many elements should go into the first chunk, first(n) grabs the first n elements, and drop(n) returns everything after that. For your example where the first chunk has 3 elements:
allay = [ {name: "Iron Man", power: "Tech"}, {name: "Spiderman", power: "Iron Man as Uncle"}, {name: "Thor", power: "God"}, {name: "Hawk Eye", power: "None"}, {name: "Black Widow", power: "love her"} ] first_part = allay.first(3) second_part = allay.drop(3) result = [first_part, second_part] # => [ [{name: "Iron Man", power: "Tech"}, {name: "Spiderman", power: "Iron Man as Uncle"}, {name: "Thor", power: "God"}], [{name: "Hawk Eye", power: "None"}, {name: "Black Widow", power: "love her"}] ]
Method 2: Use slice with Ranges
Another straightforward approach is using array ranges with slice (or the bracket notation, which acts the same way):
result = [allay[0..2], allay[3..-1]] # Produces the exact desired output
The range 0..2 includes elements from index 0 to 2 (inclusive), and 3..-1 covers from index 3 all the way to the end of the array.
Why this fits your needs
Unlike partition or group_by, these methods don't filter elements based on hash values—they just split the array at a specific point while keeping the original order intact. This is perfect when you just need to split into two ordered chunks regardless of the content of each hash.
内容的提问来源于stack exchange,提问作者Sumeet Masih

