How to reject from this array?

I have:

array = [“this ends in log”, “this ends in dog”, “this is a log”]

I want to discard strings that end in the same word. How far off is my
attempt?

array.reject { |i| i[0] =~ /\s\w$/ == i[1] =~ /\s\w$/ }

The 08/03/12, simpleton wrote:

I have:

array = [“this ends in log”, “this ends in dog”, “this is a log”]

I want to discard strings that end in the same word. How far off is my attempt?

array.reject { |i| i[0] =~ /\s\w$/ == i[1] =~ /\s\w$/ }

Three things come to my mind:

#1

Iterator i will take array elements as value:

i = “this ends in log”
i = “this ends in dog”
i = “this is a log”

So, you can work on variable i directly in the block.

#2

In your block, you must iterate the whole array instead of comparing
only adjacent elements of the array.
Of course, iterating the “whole array” is not optimised at all but it
will run fine while the current implementation is buggy.

#3

Once a “last word” from string becomes uniq, you aren’t going to delete
the last uniq element.

You need more advanced stuff than a simple comparison expression in the
block.
Also, you might need another array declared before the block where to
store the duplicated “last word” in order to know that the last uniq
“last word” was in fact a duplicated “last word”.

A simpler approach would be to:

  • first iterate the array to detect duplicated “last word” and store
    them (or their index) in another_array;
  • iterate the array again and remove known elements included in
    another_array.


Nicolas Sebrecht