I will confine my remarks to your last sentence: "Where am I going wrong?"
arrTV = ['Thor: The Dark World', 'Ender's Game', 'Jackass Presents: Bad Grandpa', \
'Last Vegas', 'Free Birds', 'Free Birds' ]
[Edit: As @Michael pointed out, you must escape all apostrophes in the elements of arrTV
(in particular, 'Ender\'s Game'
). Alternatively, you can can enclose the strings in double quotes:
arrTV = ["Thor: The Dark World", "Ender's Game", "Jackass Presents: Bad Grandpa", \
"Last Vegas", "Free Birds", "Free Birds" ]
I would recommend doing the latter. End of Edit]
It appears you first tried this:
arrTV.each do |i|
count = 0
if arrTV[i] == arrTV[i+1]
puts "equal"
count = count + 1
end
puts count
end
The first time through the (do..end
) block, i
is set equal to the first element of arrTV
, which is 'Thor: The Dark World'
, so you are attempting to execute
if arrTV['Thor: The Dark World'] == arrTV['Thor: The Dark World'+1]
which will raise an error. Consider doing this instead
if arrTV[count] == arrTV[count+1]
Better, but there are still a couple of problems. Firstly, every time the block is passed to an element of arrTV
, count
is reset to zero. You can fix that by moving count = 0
before arrTV.delete_at(i+1)
. Also, move puts count
to the end of the if
statement (right before end
).
Secondly, what happens when count = 5
? At that point you are executing
if arrTV[5] == arrTV[6],
but arrTV
only contains 6 elements, the last one indexed 5
. arrTV[6]
is not defined. There are many ways to fix this problem. One is to add:
break if count == 5
after
count = count + 1
It looks like you next tried to do this within the block
if arrTV[i] = arrTV[i+1]
arrTV.delete_at(i+1)
(Incidentally, notice that you want ==
, not =
in the first statement.) Even if we replace i
with count, you are attempting to delete some elements of arrTV
while interating over it. That's a no-no. What you need to do is start with this:
(0..arrTV.size-2) each do |i|
with this, you no longer need count
. Nor do you need to break out of the loop once you've processed the next-to-last element of arrTV
. More importantly, since you are not iterating over the elements of arrTV
, you can delete them within the loop:
arrTV.delete_at(i+1)
(This way, you could also add elements to arrTV
, or modify elements.) I will leave it to you to fix it from here. I would like to point out, however, that the approach you are taking will only eliminate duplicates if they are adjacent elements of arrTV
. If order is unimportant, you need to modify your approach.
Lastly, one Ruby convention is to use only lower case letters for variable names, and to add underscores where necessary for readability. You might use something like arr_tv
, rather than arrTV
.