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

标签 ruby hash

我有一个按工作键入并按薪水排序的人员哈希:

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

“做某事”可以正常工作,但 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 方法,该方法返回第一项并将其从哈希中删除。如果顺序很重要,您也许可以尝试在创建哈希时将其反向排序。

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

相关文章:

ruby - 为 6 :Fixnum (Rails) in a view with jQuery + ERB? 获取未定义的方法 `gsub'

mysql - 无法按虚拟属性对事件管理中的记录进行排序

ruby-on-rails - RSpec - stub 模块中的#super调用#prepend monkeypatch

windows - Windows 10 使用什么哈希算法来存储密码?

javascript - 获取资源,计算哈希值,返回 promise

javascript - 设计问题 : client side or server side?

ruby - 如何在不将换行符插入字符串的情况下使用 'puts' 添加额外的换行符?

c# - 经典的 asp 使用 capicom 进行 md5 哈希-结果不同于 .net System.Security.Cryptography

Python:pdf文件的哈希与下载的对象

java - 创建一个通用数组以在 Java 中与哈希表一起使用