简体   繁体   English

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

[英]How to access index value of array in conditional test using Ruby

Background: I am trying to write a simple function that generates a list of calendar days, which I have mostly working except for one if/else loop. 背景:我正在尝试编写一个生成日历天列表的简单函数,除了一个if / else循环之外,我主要使用它。

The relevant variables and their initial declaration values: 相关变量及其初始声明值:

monthsOfYear = %w[January February March April May June July August September October November December]
currentMonthName = "" # empty string
daysInMonth = 0 # integer

The relevant loop: 相关循环:

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

I've marked the part that I'm having trouble with between ?? 我标记了我之间遇到问题的部分? ?? ?? Basically, I am trying to figure out how to access the numerical value of the index as it loops and test whether that index number matches the few specific cases. 基本上,我试图找出如何在循环时访问索引的数值并测试该索引号是否与少数特定情况匹配。 I have searched the documentation extensively trying to find a method that returns the index number value (NOT the value stored at x index), in other words I want to be able to read x in Array[x], not what's stored at Array[x] 我在文档中进行了广泛的搜索,试图找到一种返回索引号值的方法(不是存储在x索引中的值),换句话说,我希望能够读取Array [x]中的x,而不是Array [x]中存储的内容。 X]

Perhaps in this specific case it would be better to test whether month == "April" || 也许在这个特定的情况下,最好测试月份==“四月”|| "June" || “六月”|| "September" || “九月”|| "November" rather than trying to build the case from parsing the array index number? “十一月”而不是试图通过解析数组索引号来构建案例?

But in general, what method can be called to find out the index number value? 但总的来说,可以调用什么方法来找出索引号值? Or is that even possible? 甚至有可能吗?

Joel's answer is a better implementation but to keep with your code and to answer your question, Enumerable has an an each_with_index method ( Enumberable#each_with_index ): Joel的答案是更好的实现,但为了保持代码并回答你的问题,Enumerable有一个each_with_index方法( Enumberable#each_with_index ):

monthsOfYear.each_with_index do |month, index|

then you can use index in your if/else conditionals. 那么您可以在if / else条件语句中使用index。 Note that arrays are zero based so January is actually going to be 0 . 请注意,数组基于零,因此1月实际上将为0

To get the index of an array item, use the index method: 要获取数组项的index ,请使用index方法:

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

If you're looking for date calculations specifically, Ruby has a built-in way: 如果你正在寻找具体的日期计算,Ruby有一个内置的方式:

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

If you're looking to iterate with the month and index, Anthony's answer is correct. 如果你想用月份和索引进行迭代,安东尼的回答是正确的。

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

If you're looking for a way to improve your code, use a case statement: 如果您正在寻找改进代码的方法,请使用case语句:

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

In Ruby, you can set anything equal to the result of a case statement, and also a case statement can match numbers, so it's possible to write: 在Ruby中,您可以设置等于case语句结果的任何内容,而且case语句也可以匹配数字,因此可以这样写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM