【问题标题】:hash key value seems to be nil, but it shouldn't哈希键值似乎为零,但它不应该
【发布时间】: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


【解决方案1】:

@rows 是哈希数组。

所以@rows[0]@rows 的第一个元素,即{"ID" =&gt; 1, "date" =&gt; 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

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

【讨论】:

  • 谢谢,这正是我想要的! ye 10 是日期,6 是月份。我使用这种格式是因为它是我可以使用 sqlManager 从我的 sql 数据库中获得的最简单的格式。我正在为一个简单的学校项目做这个,使用我在学校学到的东西。例如,我不知道变异数组、.map、拆分等:D
  • “最简单”在这里非常值得商榷。到 12 月你会遇到麻烦,因为明年 1 月已经过去。尽可能使用 YYYY-MM-DD 格式,尤其是在这里。
  • 我的程序只能工作到 7 月,所以我现在的格式就可以了。
猜你喜欢
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
  • 2018-03-10
  • 2012-09-01
相关资源
最近更新 更多