我想拆分哈希数组。
.split
没有处理它。
我希望在保持顺序的同时将其拆分为两个,因此可能.partion
,.select
,group_by
对我不起作用。
来自此的东西
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"}
]
以此作为输出
=> [
[
{name: "Iron Man", power: "Tech"},
{name: "Spiderman", power: "Iron Man as an Uncle"},
{name: "Thor", power: "God"}
],
[
{name: "Hawk Eye", power: "None"},
{name: "Black Widow", power: "love her <3"}
]
]
答案 0 :(得分:9)
您可以使用Enumerable#each_slice
来获得所需的行为:
left, right = allay
.each_slice(allay.length.succ / 2)
.to_a
当然,还有其他方法可以做到这一点,但它们并不是那么好。这是另一个:
pivot = allay.length.succ / 2
left, right = allay
.partition
.with_index { |_, i| i < pivot }
另一个:
left, right = [], allay.dup
left << right.shift until left.length >= right.length
基准!
each_slice 785.207k (± 5.6%) i/s - 3.920M in 5.006885s
with_index 694.555k (± 6.6%) i/s - 3.474M in 5.023968s
push_shift 1.674M (± 6.2%) i/s - 8.343M in 5.004380s
take_drop 3.468M (± 6.8%) i/s - 17.303M in 5.013369s
答案 1 :(得分:3)
答案 2 :(得分:0)
您可以对范围使用[]
表示法。
arr = [*1..6]
s = arr.size
[arr[0..s/2-1], arr[s/2..-1]]
#=> [[1, 2, 3], [4, 5, 6]]
arr = [*1..7]
s = arr.size
[arr[0..s/2-1], arr[s/2..-1]]
#=> [[1, 2, 3], [4, 5, 6, 7]]