在我的Ruby on Rails应用程序中,我有一个数组:
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中做到这一点?
答案 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 :(得分: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"]]
答案 2 :(得分:2)
Array#rassoc
搜索其元素也是数组的数组。
arr = [["Beżowy", "beige"], ["Biały", "white"], ["Brązowy", "brown"], .....
arr.push(arr.delete(arr.rassoc("other")))
答案 3 :(得分: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"]]