ruby float算术数组

时间:2013-04-10 17:41:03

标签: ruby

我在数组成员(Floats)上做数学。类型看起来正确。我仍然得到奇怪的错误。根本没有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想告诉我,我根本不能使用Arrays进行Float算术吗?此外,重写相同的一个表达式也失败了。

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

3 个答案:

答案 0 :(得分:2)

你有一个拼写错误 - @lenght而不是@length

答案 1 :(得分: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]

答案 2 :(得分:1)

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