Chickenfister Joe Chickenfister Joe - 2 years ago 63
Ruby Question

hash key value seems to be nil, but it shouldn't

So i searched for like an hour now, but i sadly couldn't find the solution. Right now i'am programming an Algorithm, that removes every hash from an array, that contains a date that is higher than the actual date.

Here is the code:

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
p @rows

The problem is, that
@rows[ i ]["date"].to_i
seems to be nil. But it works when i do
@rows[ 0 ]["date"].to_i

Here are some things that i've already tried but didn't worked out:

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

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

also, here is the error i got every single time:

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>'

I'm so confused i hope someone can help me qq

Answer Source

@rows is Array of Hashes.

So @rows[0] is first element of @rows, which is {"ID" => 1, "date" => 10.6}.

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

Update Oh, and what does 10.6 and 25.5 mean? Does it day and month of current year? If so - you code is wrong. Also, you solution is very bad. You try to mutate @rows, when iterate over it.

The solution can look like this:

current_time =
current_day, current_month =, current_time.month

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

p @rows

But I prefer you to change format of date, that you use.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download