camdaochemgio camdaochemgio - 1 year ago 74
Ruby Question

Is Rails group_by deprecated?

I have an array that I want to group and it seems like the 'group_by' function is OK for my situation.

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 it's deprecated in 4.0.2.

Which function should I use?

Answer Source

It's not deprecated.

Ruby prior to 1.8.7 didn't have group_by builtin, so rails added it. Ruby 1.8.7 added group_by, but whereas the rails group_by returned ordered hashes, the ruby 1.8.7 returned plain hashes (since ordered hashes weren't yet in ruby 1.8.7), so rails continued to overwrite the method.

Ruby 1.9 did have group_by, so rails no longer needed to overwrite it, but this code was left there for people still running 1.8.7.

Rails 4 dropped ruby 1.8.7 compatibility, so code like this was removed from rails. It's not deprecated, but it's no longer in rails because it has become part of the ruby standard library.