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
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’
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.