Ruby 2.4 Enumerable#sum breaks in Rails 5.1

余生颓废 提交于 2021-02-07 20:11:36

问题


In Rails 5.1.4 using Ruby 2.3.5, I get this behavior:

>> [].sum
#> nil

I'd like to upgrade to Ruby 2.4, where Enumerable#sum is implemented natively. Testing this in IRB using Ruby 2.4.2, I get this result:

>> [].sum
#> 0

That's OK, and I can handle the different result. But going back to the Rails console in Rails 5.1.4 using Ruby 2.4.2, I get this:

>> [].sum
#> NoMethodError: undefined method `each' for nil:NilClass

However, in a newly created Rails 5.1.4 project, I don't get this error. What's going on here?


回答1:


Looking at the source for the Active Support enumerable extensions it definitely seems like something odd is going on because you shouldn't have been getting the behaviour you described for Rails 5.1.4 using Ruby 2.3.5 i.e. you should have been getting 0 not nil there too.

Active Support's Array#sum checks if Ruby's own sum can be used by checking first.is_a?(Numeric). This will be false for an empty array so the call to super will call Enumerable#sum and both implementations of that have a default of 0.

Try [].method(:sum).source_location in the Rails console of your existing project to see if Array#sum is being overridden somewhere.

if that returns the expected line from active_support/c‌​ore_ext/enumerable.r‌​b then the next step will be to check [].method(:sum).super_method.source_location and see if a customised Enumerable#sum is the culprit.




回答2:


I think that your application have some overhidden on sum method. Look the example below with 2 new applications using the 2 different versions of ruby

/testapp# ruby --version
ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-linux]
/testapp# rails --version
Rails 5.1.4
/testapp# rails c
irb(main):001:0> [].sum
=> 0

and the other version

/testapp# ruby --version
ruby 2.3.5p376 (2017-09-14 revision 59905) [x86_64-linux]
/testapp# rails --version
Rails 5.1.4
/testapp# rails c
irb(main):001:0> [].sum
=> 0


来源:https://stackoverflow.com/questions/47982072/ruby-2-4-enumerablesum-breaks-in-rails-5-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!