【发布时间】:2016-09-24 15:38:57
【问题描述】:
所以我现在搜索了大约一个小时,但遗憾的是我找不到解决方案。现在我正在编写一个算法,该算法从数组中删除每个散列,其中包含一个高于实际日期的日期。
代码如下:
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
【问题讨论】:
-
注意:这应该是
Time.now.strftime(...)。空参数被省略。::分隔符应仅用于命名空间导航。 -
这可能是我见过的比较日期的最古怪的方法之一。你是用 10.6 来代表“6 月 6 日”吗?如果您使用 ISO 8601 日期格式,您可以将字符串与字符串进行比较:
%Y-%m-%d
标签: ruby for-loop multidimensional-array hash