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.
- if want call
input_arr.uniqueinput_arrbeing array, have define method onarray. haveinput_arrwithin method body, comes nowhere. putsin last line of code outputs terminal, makes method returnnil, makes behave differentlyuniq.
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
Post a Comment