I want to translate these 2 for-loops to a loop with a block, but I keep on getting a Type error.
This is the original code: EDIT I have added what h1 and h2 are
h1 = gethashfromfile('arrtime.txt')
h2 = gethashfromfile('deptime.txt')
k1 = h1.keys
k2 = h2.keys
kcommon = k1 & k2
k_not_in_both = (k1 - kcommon) | (k2 - kcommon)
arr = kcommon.to_a
for i in 0...arr.size
stay = h2[arr[i]] - h1[arr[i]]
if stay < 0
puts arr[i] + ': data issue'
else
puts arr[i] + ': stay ' + stay.to_s + ' minutes'
end
end
arr2 = k_not_in_both.to_a
for i in 0...arr2.size
puts arr2[i] + ': data issue'
end
This is what I have so far:
arr.each do |i|
stay = h2[arr[i]] - h1[arr[i]]
if stay < 0
puts arr[i] + ': data issue'
else
puts arr[i] + ': stay' + stay.to_s + ' minutes'
end
end
arr2 = k_not_in_both.to_a
arr2.each { |x| puts arr2[x] + ': data issue'}
This is the error I am receiving:
TypeError: no implicit conversion of String into Integer
from (irb#1):202:in `[]'
from (irb#1):202:in `block in irb_binding'
from (irb#1):201:in `each'
from (irb#1):201
h1andh2are or really what the desired result is. While you may get help understanding loops, us understanding the actual problem you are facing will lead to more constructive idiomatic answers in generalforloops andeachloops get interpreted in exactly the same way by the interpreter. Somehow that has led to the convention that we should only useeach(eachis the internal name for these loops in MRI). So your question isn't really about translating aforloop into aneach, but how to rewrite it in more idiomatic ruby :-)forloops are different. They don't create a local scope, and that is why we prefereachloops in Ruby!