gpt4 book ai didi

ruby - 类似于 array#pop for hash 的方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:47:42 26 4
gpt4 key购买 nike

我有一个按工作键入并按薪水排序的人的散列:

person = Struct.new(:salary)

people = {
:butchers => [
person.new(10),
person.new(6),
person.new(4)
],
:bakers => [
person.new(16),
person.new(8),
person.new(7)
],
:candlestick_makers => [
person.new(25),
person.new(21),
person.new(18)
]
}

我想从他们各自的数组中删除每个工作的最后 x 个人并做一些事情:

def this_example_method
people.each do |job, people|
people.pop(number_for(job)).each do |person|
#do something
end
end
end

'do something' 可以正常工作,但 pop 删除则不行。运行 this_example_method 后,people 哈希应该看起来像这样,但目前它没有改变:

people = {
butchers = [
<butcher_1 salary:10>
<butcher_2 salary:6>
],
bakers = [
<baker_1 salary:16>
<baker_2 salary:8>
],
candlestick_makers = [
<candlestick_maker_1 salary:25>
<candlestick_maker_2 salary:21>
]
}

最佳答案

Hash 有一个 shift 方法,它返回第一个项目并将其从 hash 中删除。如果顺序很重要,您或许可以尝试在创建散列时将其反转排序。

关于ruby - 类似于 array#pop for hash 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22685718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com