【问题标题】:How to access index value of array in conditional test using Ruby如何使用 Ruby 在条件测试中访问数组的索引值
【发布时间】: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 就足够了。
  • 感谢您的澄清

标签: ruby arrays indexing


【解决方案1】:

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

monthsOfYear.each_with_index do |month, index|

那么您可以在 if/else 条件句中使用索引。请注意,数组是从零开始的,所以一月实际上是0

【讨论】:

  • 谢谢,这正是我无法找到的信息类型,尽管我会听取您的建议并尝试以不同的方式实施。
【解决方案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

如果您希望使用月份和索引进行迭代,Anthony 的答案是正确的。

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

【讨论】:

  • 谢谢,您的所有示例都非常有帮助!
猜你喜欢
  • 2019-11-22
  • 2012-08-29
  • 2014-03-08
  • 2014-06-16
  • 2019-12-25
  • 1970-01-01
  • 1970-01-01
  • 2011-08-14
  • 2019-03-31
相关资源
最近更新 更多