Speed up development with full-stack environments for every branch.

Learn More

Selecting items from an array to recursively delete [Ruby, iterating, .each_with_index, .each and delete_at]

Forked from Basic Ruby Example.

63 Runs 673 Views 50 Copies

Scheme to take a given array, select items to delete from the array and then iterate over and remove said items.

Saved

Saved

arledgemike 8

arledgemike
published 3 years ago

#array you are working with
@arr = ["cat", "dog", "bird", "rabbit", "alligator", "mouse"]

#Method to print out array with indexs for easy selection
def display_arr
  @arr.each_with_index do |x, index|
    puts "#{index} - #{x}"
  end
end

#run display method
display_arr

#insert items to delete
puts "What should be deleted?"
@del = gets.chomp.split","

#run through the values of the @del array subtract the @del value from the index to keep the removal of items in order.
@del.each_with_index do |x, index|
  n = x.to_i - index
  @arr.delete_at n
end

#print the array out to see changes
puts "Your new array is : "
display_arr

Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).