How to check if an object already exists in an array

I am making a task list. I have declared two classes, List and Task. I
want to check if a task already exists in the task array and if it does
I don’t want to add a task with similar name. the method I am looking to
edit is create_task in class List.

class Task
attr_accessor :name, :status

def initialize(name, status="incomplete")
 @name = name
 @status = status
end

def to_s
“#{name.capitalize}: #{status.capitalize}”
end

end

class List
attr_accessor :tasksarray
def initialize
@tasksarray = []
end

def create_task(name)
    new_task = Task.new(name)
    tasksarray.push(new_task)
    puts "New task #{new_task.name} has been added with status

#{new_task.status}"
end

end

There are many ways to do this, but something like this should work:


class Task
attr_accessor :name, :status

def initialize( name_val, status_val = ‘incomplete’ )
self.name = name_val
self.status = status_val
end

def to_s
“#{ name.capitalize }: #{ status.capitalize }”
end

end

class List
attr_accessor :tasksarray
def initialize
self.tasksarray = []
end

def create_task( name )

if tasksarray.any? { |task| task.name =~ /#{ name }/i }

  fail ArgumentError, 'Task already exists with name: ' + name.to_s

else

  new_task = Task.new( name )
  tasksarray << new_task
  puts "New task #{ new_task.name } has been added with status #{ 

new_task.status }"

end

end

end


a = List.new
=> #<List:0x00000003311610 @tasksarray=[]>

a.create_task ‘A’
New task A has been added with status incomplete
=> nil

a.create_task ‘a’
ArgumentError: Task already exists with name: a
from (irb):63:in `create_task’