-1

I have a method, that takes an array of rails active record objects and sort those records based on the second parameter passed into the method. The method looks something like :

def sort_provider(providers, attr)
  provider.sort!(|a,b| a."#{attr}" <=> b."#{attr}")
end

When I call the method, sort_providers(providers, "name"), I get a unexpected tSTRING_BEG, expecting '('.

How do I get the method to sort the array based on the second parameter passed in?

Dan
  • 25
  • 3

2 Answers2

0

Try to use send

providers.sort_by! { |a, b| a.send(attr) <=> b.send(attr) }
Ursus
  • 29,643
  • 3
  • 33
  • 50
0

If attr is a symbol:

providers.sort_by(&attr)
Alexander Popov
  • 23,073
  • 19
  • 91
  • 130