ruby - Return unique values of an array without using `uniq` -


for challenge, i'm trying return unique values of array without using uniq. have far, doesn't work:

def unique    unique_arr = []    input_arr.each |word|      if word != unique_arr.last        unique_arr.push word      end    end    puts unique_arr end input = gets.chomp input_arr = input.split.sort input_arr.unique 

my reasoning here if sorted array first before iterated through each, push unique_arr without repetition being possibility considering if it's duplicate, last value pushed match it.

am tackling wrong way?

yes, making @ least 2 mistakes.

  1. if want call input_arr.unique input_arr being array, have define method on array. have input_arr within method body, comes nowhere.
  2. puts in last line of code outputs terminal, makes method return nil, makes behave differently uniq.

it can fixed as:

class array   def unique     unique_arr = []     each |word|       unique_arr.push(word) unless unique_arr.last == word     end     unique_arr   end end 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -