Skip to content

Instantly share code, notes, and snippets.

@NoMan2000
Last active January 13, 2019 23:00
Show Gist options
  • Save NoMan2000/2e177208bd743a490602365b642953de to your computer and use it in GitHub Desktop.
Save NoMan2000/2e177208bd743a490602365b642953de to your computer and use it in GitHub Desktop.
Ruby Unique methods

Demo code

This is a quick demo for a student on how to solve a problem in ruby, creating their own built-in version of a ruby method.

require 'test/unit'
def unique_array_unique(arr)
arr.uniq # Should be self explanatory, all arrays have a uniq method for removing duplicate values
end
def unique_array_self(arr)
new_arr = [] # start by creating a new array
arr.each do |a| # loop through the existing array
unless new_arr.include?(a) # unless will only run if the statement returns false
new_arr.push(a) # If the item does not exist in the new array, add it. Otherwise, do nothing (No-op)
end
end
new_arr # return the new array at the end
end
class ArrayTest < Test::Unit::TestCase
# Must use the test_ method name to indicate that you want this to be a test
def test_unique_array_unique_will_remove_duplicate_items
arr_one = %w(bat balls gloves drinks balls) # Alternative syntax for ['bat', 'balls', 'gloves']
arr_two = unique_array_unique(arr_one) # Use the built-in unique method.
# The first position is the expected outcome, which will be no duplicate balls entry.
# The second position is the actual outcome. The third is the error message if it fails.
assert_equal(%w(bat balls gloves drinks).sort, arr_two.sort, 'Array does not match!')
p arr_one, arr_two
end
def test_unique_array_self_will_remove_duplicate_items
arr_one = %w(bat balls gloves drinks balls)
# Exactly the same as above, but uses the method that we created.
arr_two = unique_array_self(arr_one)
assert_equal(%w(bat balls gloves drinks).sort, arr_two.sort, 'Array does not match!')
p arr_one, arr_two
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment