哈希键值似乎为零,但它不应该

时间:2016-05-26 14:44:43

标签: ruby for-loop multidimensional-array hash

所以我现在搜索了一个小时,但我遗憾地找不到解决方案。现在我正在编写一个算法,它从数组中删除每个哈希,其中包含的日期高于实际日期。

以下是代码:

time = Time::now().strftime('%e.%-m.%y %k:%M')
@rows = [{"ID" => 1, "date" => 10.6}, {"ID" => 2, "date" => 25.5}]
max = @rows.length
p max
(0..max).each do |i|
    a = @rows[i]["date"].to_i 
    b = @rows[i]["date"]%1 
    a1 = time.to_i
    b1 = time%1

    if b == b1 then
        if a <= a1 then
            @rows.delete_at(i)
        end
    end         
end
p @rows

问题是,@rows[ i ]["date"].to_i似乎是零。但是当我@rows[ 0 ]["date"].to_i时它会起作用。

以下是我已经尝试但没有解决的一些事情:

a = @rows[i]["date"].to_i unless @rows[i]["date"].nil?

a = @rows.at(i)["date"].to_i unless @rows[i]["date"].nil?

另外,这是我每次都得到的错误:

lab.rb:6:in `block in <main>': undefined method `[]' for nil:NilClass   (NoMethodError)
    from lab.rb:5:in `each'
    from lab.rb:5:in `<main>'

我很困惑,希望有人可以帮助我qq

1 个答案:

答案 0 :(得分:2)

@rows是哈希数组。

所以@rows[0]@rows的第一个元素,即{"ID" => 1, "date" => 10.6}

@rows[0]['date'] == 10.6

<强>更新 哦,10.6和25.5是什么意思?是今年的日期和月份吗?如果是这样 - 你的代码是错的。 另外,你解决方案非常糟糕。当迭代它时,你试图改变@rows

解决方案可能如下所示:

current_time = Time.now
current_day, current_month = current_time.day, current_time.month

rows = [
  { 'ID' => 1, 'date' => 10.6 },
  { 'ID' => 2, 'date' => 25.5 }
]
rows = rows.select do |row|
  day, month = row['date'].to_s.split('.').map(&:to_i)
  month < current_month || (month == current_month) && (day <= current_day)
end

p @rows

但我更喜欢你改变你使用的日期格式。

相关问题