2013-04-10 33 views
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是否想告诉我,我根本不能使用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>' 
+2

你有一个错字 - '@ lenght'而不是'@ length'。这可能是你的零来自的地方。 – 2013-04-10 17:46:23

+0

@WallyAltman:让它成为答案!这绝对是。 – jmdeldin 2013-04-10 17:48:36

+0

啊wally没有看到你!我的不好 – AJcodez 2013-04-10 17:49:17

回答

1

As @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] 
+0

你能加入吗? http://chat.stackoverflow.com/rooms/27184/ruby-conceptual – 2013-04-10 18:35:00

1

的零是从您的错字到来。 @length设置为50,但没有为变量@lenght设置值(注意转置的“h”和“t”)。

2

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

+0

这里的正确答案 – AJcodez 2013-04-10 17:55:11