根据属性从数组中删除自定义数据类型元素

时间:2019-05-23 09:08:17

标签: arrays ruby custom-data-attribute custom-data-type

我正在制作日历应用程序,其功能之一是允许用户删除他选择的任何预设活动。我当前的代码获取用户在所选日期的输入,并显示当天的所有预设活动。然后,用户输入一个活动名称,代码将循环查找具有与该活动名称匹配的数据类型属性的数组元素,然后删除该元素。只要代码中有不多于同一天的day属性,代码就可以正常工作,这很奇怪。谁能向我解释为什么会这样,我应该如何解决?

我曾经尝试过对代码进行重塑以使用不同的语法功能(例如拒绝和删除),但是所有这些都会回到同一个问题,即除非在同一天有两次活动,例如如果有两个活动以monday作为day的自定义属性,ruby会说该元素具有和未定义的类

def main
  # code inside my main function to get reminder_list
  puts "Wheeks Calendar App"
  # reads in data from text file and appends to an array
  text_file = File.new("wheeks.txt", "r")
  remind_no = text_file.gets.chomp.to_i
  reminder_list = Array.new
  for x in 0..(remind_no-1)
    reminder = read_reminder(text_file)
    reminder_list << reminder
  end
  text_file.close()
end

def delete_activities reminder_list
  # function to delete elements

  puts ("\n\nYou've chosen to delete activities")
  delete_day = (string_input("Please select a day to delete activities from")).capitalize
  days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  while !days.include?(delete_day)
    delete_day = (string_input("Please select a proper day")).capitalize
  end 
  puts "Displaying activities from " + delete_day + "\n\n"
  count = 0
  for x in 0..(reminder_list.length-1)
    if (reminder_list[x].day == delete_day)
      puts "Day:" + reminder_list[x].day
      puts "Start time:" + reminder_list[x].startTime.to_s
      puts "End time:" + reminder_list[x].endTime.to_s
      puts "Activity:" + reminder_list[x].activityName
      puts "Comments:" + reminder_list[x].activityComments
      puts "\n"
      count += 1
    end
  end
  if (count == 0)
    puts "There are no activities on that day\n\n"
  else
    delete_activity = (string_input("From the activities displayed, input the activity name of the activity you want to delete")).downcase
    for x in 0..(reminder_list.length-1)
      if (reminder_list[x].day == delete_day)
        if (reminder_list[x].activityName == delete_activity)
          reminder_list.delete_at(x)
          puts "Activity " + delete_activity + " has been deleted from " + delete_day + "\n\n"
        end 
      end
    end
  end
end

1 个答案:

答案 0 :(得分:0)

我看到的问题是,您在从数组中删除元素时正在遍历索引。这会导致数组元素在删除第一项时发生移位,从而导致循环在其中一个元素删除后跳过一个元素。

我建议使用#reject!

delete_activity = string_input("From the activities displayed, input the activity name of the activity you want to delete").downcase

reminder_list.reject! do |activity|
  to_delete = activity.day == delete_day && activity.activityName == delete_activity

  if to_delete
    puts "Activity #{delete_activity} has been deleted from #{delete_day}\n\n"
  end

  to_delete
end

或者,如果您不介意忽略puts通话。

reminder_list.reject! do |activity|
  activity.day == delete_day && activity.activityName == delete_activity
end