-1

If I have an array of arrays:

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

How can I eliminate the repeated values, keeping the ones at the END of the array, resulting in:

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

Thanks!

I have tried numerous approaches, such as following absurd lines, with no success.

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

and many more . . .

khagler
  • 3,996
  • 29
  • 40
user3291025
  • 997
  • 13
  • 20
  • 1
    You need to define what you mean by "repeated values". Based on your example, it appears you mean that `b` is a repeated value of `a` if `b` follows `a` and `b.last==a.last`. – Cary Swoveland Jun 21 '14 at 01:20
  • FYI, the reason you're getting a syntax error is because "in" doesn't work like that in Ruby. I'm guessing you're looking for something similar to Array comprehensions in Python? – Ajedi32 Jun 21 '14 at 01:24
  • @Ajedi32, that's right, I'm relatively new to Ruby and learned to program in Python last year. – user3291025 Jun 21 '14 at 01:25
  • 2
    Cool. I don't want to get into too much detail here since the comments aren't really meant for extended discussion, but basically blocks in Ruby work a lot more like loops than Array comprehensions. This might interest you: http://stackoverflow.com/q/4769004/1157054 And the reverse: http://stackoverflow.com/questions/4769478/learning-ruby-from-python-differences-and-similarities?lq=1 – Ajedi32 Jun 21 '14 at 01:31

3 Answers3

4

This should do it:

a.reverse.uniq(&:last).reverse
=> [[4, "foo"], [5, "bar"], [6, "baz"]]
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
1

It can be solved by using Ruby's Hash technique also :

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

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"]]

update As @Uri suggested -

Hash[array].invert.invert.to_a
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
1
 arr.group_by{|x|x[1]}.values.map(&:last)
bluexuemei
  • 419
  • 5
  • 6