类似于array#pop的方法用于hash

时间:2014-03-27 11:06:20

标签: ruby hash pop

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

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>
  ]
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

请按以下步骤操作:

def this_example_method
  people.each do |job, persons|
    persons.tap { |ob| ob.pop(x) }.each do |person|
      #do something
    end
  end
end

示例:

hash = { :a => [1,2,3], :b => [3,5,7] }
hash.each do |k,v|
  v.tap(&:pop).each { |i| # working wit i }
end

hash # => {:a=>[1, 2], :b=>[3, 5]}