2014-06-30 63 views
2

在我的Ruby on Rails應用程序我有一個數組:找到一個數組元素並將其設置爲最後一個Ruby?

Car.color.values.map{|x| [x.text, x]}.sort 

此代碼給我下面的數組:

[["Beżowy", "beige"], ["Biały", "white"], ["Brązowy", "brown"], ["Czarny", "black"], ["Czerwony", "red"], ["Fioletowy", "violet"], ["Grafitowy", "graphite"], ["Inny", "other"], ["Niebieski", "blue"], ["Perłowy", "pearl"], ["Srebrny", "silver"], ["Szary", "grey"], ["Zielony", "green"], ["Żółty", "yellow"]] 

現在我想找到這個元素:["Inny", "other"]並將其設置爲最後一個元素的數組。 我如何在Ruby中做到這一點?

回答

3

對於一個更通用的解決方案(當你不知道該元素的確切值),可以使用partition,然後串聯的答案回:

arr = [["Beżowy", "beige"], ["Biały", "white"], ["Brązowy", "brown"], ["Czarny", "black"], ["Czerwony", "red"], ["Fioletowy", "violet"], ["Grafitowy", "graphite"], ["Inny", "other"], ["Niebieski", "blue"], ["Perłowy", "pearl"], ["Srebrny", "silver"], ["Szary", "grey"], ["Zielony", "green"], ["Żółty", "yellow"]] 
arr.partition { |k, v| v != "other" }.inject(:+) 
# => [["Beżowy", "beige"], ["Biały", "white"], ["Brązowy", "brown"], ["Czarny", "black"], ["Czerwony", "red"], ["Fioletowy", "violet"], ["Grafitowy", "graphite"], ["Niebieski", "blue"], ["Perłowy", "pearl"], ["Srebrny", "silver"], ["Szary", "grey"], ["Zielony", "green"], ["Żółty", "yellow"], ["Inny", "other"]] 
+0

非常好的解決方案。非常感謝! –

5
a = [["Beżowy", "beige"], ["Biały", "white"], ["Brązowy", "brown"], ["Czarny", "black"], ["Czerwony", "red"], ["Fioletowy", "violet"], ["Grafitowy", "graphite"], ["Inny", "other"], ["Niebieski", "blue"], ["Perłowy", "pearl"], ["Srebrny", "silver"], ["Szary", "grey"], ["Zielony", "green"], ["Żółty", "yellow"]] 
a.push(a.delete(["Inny", "other"])) 
# => [["Beżowy", "beige"], ["Biały", "white"], ["Brązowy", "brown"], ["Czarny", "black"], ["Czerwony", "red"], ["Fioletowy", "violet"], ["Grafitowy", "graphite"], ["Niebieski", "blue"], ["Perłowy", "pearl"], ["Srebrny", "silver"], ["Szary", "grey"], ["Zielony", "green"], ["Żółty", "yellow"], ["Inny", "other"]] 
1
i = a.index(["Inny", "other"]) 
a.take(i) + a.drop(i + 1) << ["Inny", "other"] 
=> [["Beżowy", "beige"], ["Biały", "white"], ["Brązowy", "brown"], ["Czarny", "black"], ["Czerwony", "red"], ["Fioletowy", "violet"], ["Grafitowy", "graphite"], ["Niebieski", "blue"], ["Perłowy", "pearl"], ["Srebrny", "silver"], ["Szary", "grey"], ["Zielony", "green"], ["Żółty", "yellow"], ["Inny", "other"]] 
2

Array#rassoc搜索其元素也是數組的數組。

arr = [["Beżowy", "beige"], ["Biały", "white"], ["Brązowy", "brown"], ..... 
arr.push(arr.delete(arr.rassoc("other"))) 
相關問題