【发布时间】:2018-10-21 07:27:06
【问题描述】:
对于上下文,我正在尝试解决这个问题。
牙医预约时间表验证软件
实现超类
Appointment和子类OneTime、Day和Month。一个Appointment有一个description(例如,“根管”)和dates信息(您可以使用Date 对象或int Year、Int Month、Int Day)。用各种约会填充Appointment对象数组。在每个子类中编写一个方法 OccursOn,用于检查约会是否发生在该日期 (OneTime)、日期 (Day) 或月份 (Month)。要求用户输入要检查的日期(例如,2006 10 5),并询问用户是否要检查
OneTime、Day或Month约会。根据用户选择的内容,每个子类中的 OccursOn 应该运行并显示任何匹配的约会和相关描述。
这是我目前所拥有的。
class Appointment
attr_accessor :day, :month, :year, :info
def initialize(day, month, year, info)
@day = day
@month = month
@year = year
@info = info
end
def occursOn
end
end
class OneTime < Appointment
def OneTime.occursOn(day, month, year)
if @day.to_i == day.to_i && @month.to_i == month.to_i && @year.to_i == year.to_i
puts "Good"
else
puts "Not Good"
end
end
end
class Day < Appointment
def Day.occursOn(day)
if @day.to_i == day.to_i
puts "Good"
else
puts "Not Good"
end
end
end
class Month < Appointment
def Month.occursOn(month)
if @month.to_i == month.to_i
puts "Good"
else
puts "Not Good"
end
end
end
app1 = OneTime.new("10", "11", "2018","Root Canal")
app2 = Day.new("10", "11", "2018", "Root Canal")
app3 = Month.new("10", "11", "2018", "Root Canal")
app4 = OneTime.new("11", "11", "2018", "Cleaning")
app5 = Day.new("11", "11", "2018", "Cleaning")
app6 = Month.new("11", "11", "2018", "Cleaning")
a = Array.new
a << app1 << app2 << app3 << app4 << app5 << app5 << app6
puts "Please enter the day of the appointment that you would like to search for"
day = gets.chomp
puts "Please enter the month of the appointment that you would like to search for"
month = gets.chomp
puts "Please enter the year of the appointment that you would like to search for"
year = gets.chomp
puts "Enter a number 1-3 to choose an answer out of OneTime, Day, or Month to search in that catagory respectivly"
answer = gets.chomp
if answer == "1"
OneTime.occursOn(day, month, year)
elsif answer == "2"
Day.occursOn(day)
elsif answer =="3"
Month.occursOn(month)
else
puts "Wrong answer"
end
我正在尝试验证与“日”、“月”和“年”相对应的用户输入与用户输入方法对应的每个数组值中的数字是否匹配。所以'OneTime.OccursOn' 应该只搜索由'OneTime.new' 组成的数组。我不能使用.include?因为日期和月份值相同的可能性。
这看起来很有用,但我不知道如何用我的子类实现这样的东西。
array = [
["A", "X"],
["B", "Y"],
["C", "Z"]
]
str = "Y"
arr = array.find{|a| a[1] == str}
puts arr[0] if arr
# => B
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
您的示例代码不起作用。您可以轻松确认。原因是,例如在
class Day < Appointment中,变量a是未定义的。因此,Day.OccursOn(day)会引发 NameError。因此,您最好更新您的问题,并提供至少不会引发异常的代码。 -
将其编辑为与您给出的答案类似的内容,第一篇文章中有 if 语句是我在测试问题的可能解决方案时留下的。
标签: ruby-on-rails arrays ruby