Ruby Arrays:仅从数组数组的末尾保留重复值

Ruby Arrays: keep repeated values only from the end of an array of arrays

如果我有一个数组:

1
[[1,"foo"], [2,"bar"], [3,"foo"], [4,"foo"], [5,"bar"], [6,"baz"]]

如何消除重复值,使其保持在数组末尾,从而导致:

1
[[4,"foo"], [5,"bar"], [6,"baz"]]

谢谢!

我尝试过很多方法,比如按照荒谬的路线,但都没有成功。

1
2
3
a.delete_if {|q| q if q[1] in a}   # syntax error

a.each {|q| q.shift if q[1] in a[q][1]} # syntax error

还有更多。…


应该这样做:

1
2
a.reverse.uniq(&:last).reverse
=> [[4,"foo"], [5,"bar"], [6,"baz"]]


1
 arr.group_by{|x|x[1]}.values.map(&:last)


它也可以通过使用Ruby的Hash技术来解决:

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays,....

1
2
3
array = [[1,"foo"], [2,"bar"], [3,"foo"], [4,"foo"], [5,"bar"], [6,"baz"]]
Hash[array].invert.map { |k,v| [v,k] }
# => [[4,"foo"], [5,"bar"], [6,"baz"]]

按@uri建议更新-

1
Hash[array].invert.invert.to_a