0

我正在对数组成员(浮点数)进行数学运算。类型看起来正确。我仍然得到奇怪的错误。根本没有nil价值。这是什么错误?

nil can't be coerced into Float

步骤1

newFront = [412.5, 312.5]
@direction = [1.0, 0.0]
@length = 50.0
retRear = [newFront[0] - (@direction[0] * @lenght), newFront[1] - (@direction[1] * @lenght)]
# => TypeError: nil can't be coerced into Float
#   from (irb):13:in `*'
#   from (irb):13
#   from /usr/bin/irb:12:in `<main>'

第2步

newFront[0].class # => Float
@direction[0].class # => Float
@length.class # => Float

第 3 步

nfx = Float(newFront[0]) # => 412.5
dx = Float(@direction[0]) # => 1.0
nfy = Float(newFront[1]) # => 312.5
dy = Float(@direction[1]) # => 0.0
@l = 50.0
retRear = [nfx - (dx * @l), nfy - (dy * @l)] # => [362.5, 312.5]

这就是我想要的。Ruby 是否想告诉我我根本不能使用数组进行浮点运算?此外,将相同的表达式重写为一个表达式也失败了。

retRear = [Float(newFront[0]) - (Float(@direction[0]) * Float(@lenght)), Float(newFront[1]) - (Float(@direction[1]) * Float(@lenght))]
# => TypeError: can't convert nil into Float
#   from (irb):78:in `Float'
#   from (irb):78
#   from /usr/bin/irb:12:in `<main>'
4

3 回答 3

2

你有一个错字 -@lenght而不是@length.

于 2013-04-10T17:51:30.520 回答
1

正如@WallyAltman 指出的那样,您拼写错误@length,因此为零。

我会这样做,顺便说一句:

new_front = [412.5, 312.5]
@direction = [1.0, 0.0]
@length = 50.0
ret_rear = new_front.zip(@direction).map do |front, dir|
  front - dir * @length
end
# => [362.5, 312.5]
于 2013-04-10T17:48:47.400 回答
1

nil 来自您的拼写错误。@length 设置为 50,但没有为变量 @lenght 设置值(注意转置的“h”和“t”)。

于 2013-04-10T17:50:18.657 回答