引用数组中的实例变量

时间:2015-09-22 02:55:47

标签: arrays ruby

我有两个课程:TodoListTodoItemTodoList有一个TodoItem数组,该数组名为todo_itemsTodoItem的每个实例都有两个实例变量:name(字符串)和complete(布尔值)。

我正在尝试编写一个TodoList类方法来从此数组中删除TodoItem。下面针对TodoList.remove_item方法的未注释代码有效,但它使用each遍历todo_items数组,检查每个TodoItem实例name 。我觉得必须有更好的方法来做到这一点。

我试图在include?上使用delete_attodo_items来使其工作,但由于其内容是TodoItem的类实例,因此无法正常工作。

编辑:类TodoListTodoItem的代码如下:

TodoList的:

require "./todo_item"

class TodoList
  attr_reader :name, :todo_items

  def initialize(name)
    @name = name
    @todo_items = []
  end

  def add_item(name)
    todo_items.push(TodoItem.new(name))
  end

  def remove_item(name)
    index = 0
    found = false
    todo_items.each do |todo_item|
      if todo_item.name == name
        found = true
      end
      if found
        break
      else
        index += 1
      end
    end
    if found
      todo_items.delete_at(index)
      return true
    else
      return false
    end #if
  end

#    CODE BELOW DOES NOT WORK
#    if (todo_items.include?
#      arr_index = todo_items.(#??)
#      todo_items.delete_at(arr_index) #invalid ref
#      puts "#{name} was removed from the list"
#    else
#      puts "That item does not exist in the to do list."
#    end #if
#  end #def remove_item

end #class TodoList

的TodoItem:

class TodoItem
  attr_reader :name

  def initialize(name)
    @name = name
    @complete = false
  end #initialize

  def to_s
    if complete?
      "[C] #{name}"
    else
      "[I] #{name}"
    end
  end

  def complete?
    @complete
  end

  def mark_complete!
    @complete = true
  end

  def mark_incomplete!
    @complete = false
  end

end #class TodoItem

2 个答案:

答案 0 :(得分:0)

您可以使用 Array#delete_if ,如:

def remove_item(name)
  todo_items.delete_if { |x| x.name == name}
end

如果你仍然希望返回布尔值,那么

def remove_item(name)
  found = todo_items.index { |x| x.name == name }  # return nil if not found or the index.
  todo_items.delete_if { |x| x.name == name}
  !!found # turn to boolean
end

PS: remove_item应该是类TodoList的实例方法。

答案 1 :(得分:0)

def remove_item(name)
  !!todo_items.reject!{|e| e.name == name}
end