将特定的集合/数组项放在rails中的最后一个位置

时间:2015-05-06 11:45:01

标签: ruby-on-rails ruby sorting

我在rails中有一个集合/数组,转换为json,它看起来像这样:

@collection = [{"order_number":"123","item":"Paper"},{"order_number":"567","item":"Ruler"},{"order_number":"344","item":"Pen"},{"order_number":"342","item":"Pencil"},{"order_number":"877","item":"Keyboard"}]

我想选择order_number" 342"并将它放在集合的最后位置,因此新集合看起来像这样:

@collection = [{"order_number":"123","item":"Paper"},{"order_number":"567","item":"Ruler"},{"order_number":"344","item":"Pen"},{"order_number":"877","item":"Keyboard"},{"order_number":"342","item":"Pencil"}]

理论上,它看起来像这样:

@collection.last = @collection[3]

但这显然不是花哨的ruby风格,也不会像我的例子那样重新排序数组。 此外,我不知道该项目的索引,因为它可以根据用户购物的内容而改变。

5 个答案:

答案 0 :(得分:3)

怎么样:

@collection << @collection.delete_at[@collection.index{|x| x[:order_number] == "342"}]

这首先基本上用:order_number 342搜索元素的索引,使用该索引将其删除,然后再将末尾的元素存储起来。

答案 1 :(得分:2)

您还可以使用partition方法:

@collection = @collection.partition { |h| h['order_number'] != '342' }.flatten

答案 2 :(得分:1)

只需将你的收藏分成两部分(没有342顺序,顺序为342),然后加入他们。它应该看起来像:

@collection = @collection.select {|e| e[:order_number] != '342' } + @collection.select {|e| e[:order_number] == '342' }

答案 3 :(得分:0)

如果你有一个项目的索引,那么归结为

@collection << @collection.delete_at(3)

如果你没有,你可以尝试使用

找到它
@collection.find_index{ |el| el["order_number"] == "123" }

答案 4 :(得分:0)

替代方案你也可以试试这个:

> @collection.each_with_index{ |key,value| @collection.push(@collection.delete_at(value)) if key[:order_number] == "344" }
#=>[{:order_number=>"123", :item=>"Paper"}, {:order_number=>"567", :item=>"Ruler"}, {:order_number=>"342", :item=>"Pencil"}, {:order_number=>"877", :item=>"Keyboard"}, {:order_number=>"344", :item=>"Pen"}]