ruby浮点算术数组

ruby浮点算术数组,ruby,Ruby,我在做数组成员(浮动)的数学运算。这些类型看起来是正确的。我还是犯了一个奇怪的错误。根本没有nil值。这个错误是什么 nil can't be coerced into Float 第一步 newFront = [412.5, 312.5] @direction = [1.0, 0.0] @length = 50.0 retRear = [newFront[0] - (@direction[0] * @lenght), newFront[1] - (@direction[1] * @lengh

我在做数组成员(浮动)的数学运算。这些类型看起来是正确的。我还是犯了一个奇怪的错误。根本没有
nil
值。这个错误是什么

nil can't be coerced into Float
第一步

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>'
步骤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>'
retRear=[Float(newFront[0])-(Float(@direction[0])*Float(@lenght)),Float(newFront[1])-(Float(@direction[1])*Float(@lenght))]
#=>TypeError:无法将nil转换为Float
#发件人(irb):78:in“Float”
#来自(irb):78
#from/usr/bin/irb:12:in`'

正如@Wallyatman指出的,您拼错了
@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]

正如@Wallyartman所指出的,您拼错了
@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]

零是因为你的打字错误@长度设置为50,但变量@lenght没有设置值(注意转置的“h”和“t”)。

零来自您的打字错误@长度设置为50,但变量@lenght没有设置值(注意转置的“h”和“t”)。

您有一个打字错误-
@lenght
,而不是
@length

您有一个打字错误-
@lenght
,而不是
@length

您的输入错误是
@lenght
,而不是
@length
。这可能就是你的零的来源。@Wallyartman:回答吧!绝对是这样。啊,沃利没看见你!我的坏消息我打赌至少有一个
nil
。您输入的是
@lenght
而不是
@length
。这可能就是你的零的来源。@Wallyartman:回答吧!绝对是这样。啊,沃利没看见你!我打赌至少有一个
nil
我打赌。你能加入这里吗?你能加入这里吗?