Back to Home

Destructive and Nondestructive Method

Date: Jan 14, 2015

Something to Delete

Sometimes you no longer need data that matches something. Create a `my_array_deletion_method` that takes an array and a letter, and deletes all the strings that contain that letter. This should modify the original because we now permanently hate that letter.

For example: my_array_deletion_method!(i_want_pets, "a") This will return => ["I", 4, "pets", "but", "only", 3 ]

The second method will do same thing in Hash environment. When the 'key' was matching with the word 'thing_to_delete' it will delete the pair (key and value). This will also modify the original object('source' in this case).

my_hash_deletion_method!(my_family_pets_ages, "George") This will return => {"Evi" => 8, "Hoobie" => 5, "Bogart" => 6, "Poly" => 6, "Annabelle" => 2, "Ditto" => 5}

For the first challenge, the method will delete the array element if the element contains "thing_to_delete" charactor, I use "delete_if" function. This will take an argument and the condition(element.to_s.include?) and delete if the condition was satisfied.

def my_array_deletion_method!(source, thing_to_delete) source.delete_if { |element| element.to_s.include? thing_to_delete} end

The actual challenging part about this problem was to make the function destructive. The big different between them is if the method will change the original argument or not. For instance, the method my_array_deletion_method! will change the original argument 'source' after runing. Thus the original source will be permanently changed to whatever returned value. On the other hand, non-destructive method will return the original value of argument (in this case, 'source') after running.

Launch Academy does have a great source of explaining these two different methods.

The second challenge is similar but remove the value and key pair within a hash instead of remove the element in an array. This was actually easier than array method just because value and key are more easy to work with than array element.

def my_hash_deletion_method!(source, thing_to_delete) source.delete_if { |k, v| k == thing_to_delete} end

"Delete_if " is also destructive method thus will change the original argument('source' in this case).