Codes316 Codes316 - 2 months ago 7
Ruby Question

How to delete an element from an array based off the user input in Ruby?

I'm not sure where I'm going wrong with this. I have an array and the user is prompted with a question about what number should be deleted from the array. The number is stored and the result is a new array that gets outputted with the deleted value.

def delete(number)
a = [1, 2, 1, 3, 1, 4, 2, 5]
puts "Please type number to be deleted?"
number = gets
result= a.delete(number)
puts result
end
a.delete(number)

Answer

maybe do something like this ?

  def delete(num,array)
    array.reject { |el| el == num }
    puts array
  end
  a = [1, 2, 1, 3, 1, 4, 2, 5]
  puts "Please type number to be deleted? from array #{a}"
  number = gets
  delete(number.to_i,a)
Comments