如何使用Ruby在条件测试中访问数组的索引值

时间:2015-02-18 18:15:51

标签: ruby arrays indexing

背景:我正在尝试编写一个生成日历天列表的简单函数,除了一个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 index中的值),换句话说我希望能够读取Array [x]中的x,而不是存储在Array中的x [ X]

也许在这个特定情况下,最好测试月份==“四月”|| “六月”|| “九月”|| “十一月”而不是试图通过解析数组索引号来构建案例?

但总的来说,可以调用什么方法来找出索引号值?或者甚至可能吗?

2 个答案:

答案 0 :(得分:5)

Joel的答案是一个更好的实现,但为了保持代码并回答你的问题,Enumerable有一个each_with_index方法(Enumberable#each_with_index):

monthsOfYear.each_with_index do |month, index|

然后你可以在if / else条件中使用index。请注意,数组基于零,因此1月实际上将是0

答案 1 :(得分:2)

要获取数组项的索引,请使用index方法:

monthsOfYear = [ "January", "February", "March", ... ]
monthsOfYear.index("February") #=> 1

如果您正在寻找具体的日期计算, Ruby有一种内置方式:

Date.new(date.year, date.month, -1).mday #=> the number of days in the month

如果你想用月份和指数进行迭代,安东尼的回答是正确的。

monthsOfYear.each_with_index do |month, index| {
  ...
  # The first loop: month = "January", index = 0
  ...
}

如果您正在寻找改进代码的方法,请使用case声明:

case month
when "April", "June", "September", "November" 
  daysInMonth = 30
when "February"
  if isLeapYear
    daysInMonth = 29
  else
    daysInMonth = 28
  end
else
  daysInMonth = 31
end

在Ruby中,你可以设置任何等于case语句结果的东西,并且case语句也可以匹配数字,所以可以写:

daysInMonth = case monthsOfYear.index(currentMonthName) 
when 3, 5, 8, 10 
  30
when 1
  isLeapYear ? 29 : 28
else
  31
end