为什么我使用 Ruby 注入的斐波那契数列不起作用?
这很尴尬,我不明白为什么这行代码没有返回斐波那契数列,而只是返回一系列数列。
(1..5).inject([1]) { |arr, x| x > 1 ? arr << arr.last + arr.last-1 : arr << 1; arr }
上面的代码应该找到该系列中的前六个数字。
你能告诉我我做错了什么吗?
一如既往地感谢您。
This is embarrassing, I don't get why this line of code isn't returning to me the Fibonnacci series, but instead just a series of ones.
(1..5).inject([1]) { |arr, x| x > 1 ? arr << arr.last + arr.last-1 : arr << 1; arr }
The code above is supposed to find the 1st six numbers in the series.
Could you please tell me what am I doing wrong?
Thank you as always.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
arr.last-1 不起作用,请尝试 arr[-2] 代替:
-edit-
顺便说一句,你不需要最后的 ;arr,<<默认返回数组
arr.last-1 doesnt work, try arr[-2] instead:
-edit-
btw you don't need that ;arr at the end, << returns the array by default
arr.last-1
不会为您提供数组的倒数第二个元素。它获取最后一个元素并从中减去一个。您需要类似
arr[arr.length - 2]
或奇特的 Ruby 快捷方式arr[-2]
。arr.last-1
doesn't give you the second-to-last element of the array. It takes the last element and just subtracts one from it.You want something like
arr[arr.length - 2]
or the fancy Ruby shortcutarr[-2]
.我不了解 Ruby,所以这可能完全不对劲,但这似乎可能是你的罪魁祸首:
我不认为这意味着“最后一个数组元素加上它之前的元素”,而是请
注意,如果你用 1 为数组播种,这会给你返回 1 + 1 - 1 = 1,这意味着你的项总是评估为 1,这可能不是你想要的。
让我知道这是否完全关闭,希望这会有所帮助!
I don't know Ruby, so this may be completely off, but it seems like this might be your culprit:
I don't think that this means "the last array element plus the element before it," but rather
Note that if you seed the array with 1, this would give you back 1 + 1 - 1 = 1, which means that your terms always evaluate to one, which probably isn't what you want.
Let me know if this is totally off, and hope this helps!
首先,我们不要忘记该系列实际上是从 0 开始的,并且有一个更简单的方法可以做到这一点:
享受!
First off let's not forget the series actually starts with 0 and there is a far easier way to do this:
Enjoy!
如果您真的喜欢使用
inject
,还有另一种方法:)And yet another way in case you really like to use
inject
:)最短路线:
Shortest way: