【问题标题】:How to sort two lists according to order in one of them?如何根据其中一个列表中的顺序对两个列表进行排序?
【发布时间】:2015-08-23 23:40:48
【问题描述】:

我有两个按:id 排序的哈希数组:

tweets = [{ id: 1, foo: 3, type: 'tweet' },
          { id: 2, foo: 5, type: 'tweet' },
          { id: 3, foo: 9, type: 'tweet' }]

events = [{ id: 4, foo: 6, type: 'event' },
          { id: 5, foo: 1, type: 'event' }]

我合并它们以获得结果哈希all。我想按:id的顺序排序:

[{:id=>1, :foo=>3, :type=>"tweet"},
    {:id=>2, :foo=>5, :type=>"tweet"},
    {:id=>4, :foo=>6, :type=>"event"},
    {:id=>5, :foo=>1, :type=>"event"},
    {:id=>3, :foo=>9, :type=>"tweet"}]

你能帮我实现吗?如果我这样做:

all.sort_by! { |ob| ob[:foo] }

我收到:

[{:id=>5, :foo=>1, :type=>"event"},
    {:id=>1, :foo=>3, :type=>"tweet"},
    {:id=>2, :foo=>5, :type=>"tweet"},
    {:id=>4, :foo=>6, :type=>"event"},
    {:id=>3, :foo=>9, :type=>"tweet"}]

【问题讨论】:

  • 但我想要其他结果 - 根据事件 id 的顺序:你的意思是什么?
  • @YanisVieilly 我想在其他数组中无损插入排序数组。它应该按 foo 字段排序,而不会丢失以前的顺序 id (4,5)
  • 我仍然不太确定您到底想做什么,但是如果您想按多个值排序(在您的情况下按id,然后按foo),您可以执行关注:all.sort_by! { |ob| [ob[:id], ob[:foo]] }
  • @YanisVieilly 如果我喜欢这样 - 它将按 id 排序,因为 Id - 是唯一值,所以它会在不使用 foo 字段的情况下进行排序,结果将是另一个,试试
  • 哈希是随机访问结构,排序没有任何用处。为什么要排序一个?为什么不能提取键并对它们进行排序?

标签: arrays ruby sorting


【解决方案1】:
class Array
  def reverse_each_with_index(&block)
    (0...length).reverse_each do |i|
      block.call self[i], i
    end
  end
end

def sort_by_foo(events:, tweets:)
  result = events.clone
  tweets.reverse_each do |twt|
    inserted = false
    result.reverse_each_with_index do |evn, i|
      if twt[:foo] <= evn[:foo] && evn[:type] == 'event'
        result.insert(i + 1, twt)
        inserted = true
        break
      end
    end
    result.unshift(twt) unless inserted
  end
  result
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2018-01-03
    • 1970-01-01
    • 2022-11-16
    • 2019-09-24
    相关资源
    最近更新 更多