【发布时间】:2015-04-19 21:13:28
【问题描述】:
背景:我正在尝试编写一个简单的函数来生成日历日列表,除了一个 if/else 循环之外,我大部分时间都在工作。
相关变量及其初始声明值:
monthsOfYear = %w[January February March April May June July August September October November December]
currentMonthName = "" # empty string
daysInMonth = 0 # integer
相关循环:
monthsOfYear.each do |month| #loop through each month
# first get the current month name
currentMonthName = "#{month}" # reads month name from monthsOfYear array
if ??month == 3 || 5 || 8 || 10 ?? # April, June, September, November
daysInMonth = 30
elsif ??month == 1?? # February
if isLeapYear
daysInMonth = 29
else
daysInMonth = 28
end
else # All the rest
daysInMonth = 31
end
我已经标记了我在 ?? 之间遇到问题的部分?? 基本上,我试图弄清楚如何在索引循环时访问索引的数值,并测试该索引号是否与少数特定情况匹配。我已经广泛搜索了文档,试图找到一种返回索引编号值(不是存储在 x 索引处的值)的方法,换句话说,我希望能够读取 Array[x] 中的 x,而不是存储在 Array[ x]
也许在这种特定情况下,最好测试一下month == "April" || 《六月》|| 《九月》|| “十一月”而不是试图通过解析数组索引号来构建案例?
但是一般情况下,可以调用什么方法来找出索引号的值呢?或者这甚至可能吗?
【问题讨论】:
-
"#{month}"过于复杂。只需month就足够了。 -
感谢您的澄清