Is Rails group_by deprecated?

I have an array that I want to group, and it looks like the "group_by" function is ok for my situation.

http://apidock.com/rails/Enumerable/group_by

I used it in Rails 3.2.13.

grouped_array = my_array.group_by(&:my_function) # Assume run 'my_function' have result1 on element1, element3 and result2 on element2, element4, then: # grouped_array = { # result1 => [element1, element3], # result2 => [element2, element4], # ... # } 

But I see that it is deprecated in 4.0.2.

What function should I use?

+5
source share
2 answers

It is not out of date.

Ruby before 1.8.7 did not have a built-in group_by , so the rails added it. Ruby 1.8.7 added group_by, but while group_by rails returned ordered hashes, rubies 1.8.7 returned simple hashes (since ordered hashes were not in Ruby 1.8.7 yet), so the rails continued to overwrite the method.

Ruby 1.9 had group_by , so the rails no longer needed to be rewritten, but this code remained for people still running 1.8.7.

Rails 4 reduced compatibility with Ruby 1.8.7, so code like this was removed from the rails. It is not deprecated, but is no longer on the rails because it has become part of the ruby ​​standard library.

+12
source

Will the # sort array do the trick?

 @my_array.sort { |item1, item2| item1.my_function <=> item2.my_function } 
+1
source

Source: https://habr.com/ru/post/1200400/


All Articles