0

我有:

fruits = {
  "orange" => {:season => "winter"},
  "apple" => {:season => "winter"},
  "banana" => {:season => "summer"},
  "grape" => {:season => "spring"},
  "peach" => {:season => "winter"},
  "pineapple" => {:season => "summer"}
}

我想得到:

{
  "winter"=>["orange", "apple", "peach"],
  "summer"=>["banana", "pineapple"],
  "spring"=>["grape"]
}

我做了:

def sort_fruits(fruits_hash)
  fruits=[]
  sorted = {}
  seasons = fruits_hash.map {|k, v|v[:season]}
  seasons.uniq.each do |season|
    fruits.clear
    fruits_hash.each do |fruit, season_name|
      if season == season_name[:season]
        fruits << fruit
      end
    end
    p sorted[season] = fruits ## season changes to new season, so this should have created new key/value pair for new season.
  end
  sorted
end

我得到:

{
  "winter"=>["grape"],
  "summer"=>["grape"],
  "spring"=>["grape"]
}

我无法弄清楚为什么添加具有唯一键的新键/值对会覆盖哈希中的现有对。任何有关解释的帮助将不胜感激。

4

2 回答 2

1

您的问题是您fruits对所有值重复使用相同的数组。即使你清除它,它仍然是同一个数组。如果不是fruits.clear您使用fruits = [],那么您将不会遇到问题。

您可以在以下示例中看到问题:

arr = ['val']
hash = {
  key1: arr,
  key2: arr
}
p hash # => { key1: ['val'], key2: ['val'] }

arr.clear
p hash # => { key1: [], key2: [] }

您也可以使用sorted[season] = fruits.cloneor sorted[season] = [*fruits]... 任何使用新数组的东西。

您必须跟踪何时使用“变异”方法(那些就地更改对象的方法,例如clear) - 这是使用散列和数组时的常见陷阱

于 2018-10-14T19:49:05.777 回答
1

在 Ruby 中,可变对象是通过引用传递的。这意味着当您seasonseach块中迭代此行时:

sorted[season] = fruits

保存到每个季节sorted[season]的引用。fruits循环结束后each,每个季节都有一个对相同fruits数组的引用,其中包含在迭代器的最后一步计算的项目。在你的情况下,它是["grape"].

于 2018-10-14T19:58:29.360 回答