将for-loop转换为块循环?红宝石

时间:2017-01-26 13:43:41

标签: ruby

我想将这2个for循环转换为带有块的循环,但我一直在收到Type错误。

这是原始代码: 编辑我添加了h1和h2

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

这是我到目前为止所做的:

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

这是我收到的错误:

 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

1 个答案:

答案 0 :(得分:3)

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)

plt.show()

arr.each do |i| # do something with i end 不是索引,它是元素本身!

您可以仅i替换arr[i]

为避免犯这个错误,您可以使用更多描述性变量名称:

i

letters = ['a', 'b', 'c'] letters.each do |letter| puts letter end # => # a # b # c 会抛出错误,因为letters[letter]是一个数组而letters期望一个整数作为索引,而不是字符串。