Dan Dan - 6 months ago 28
Ruby Question

Pass active record attributes in a method

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}")

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?

Answer Source

Try to use send

providers.sort_by! { |a, b| a.send(attr) <=> b.send(attr) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download