WestonGanger WestonGanger - 7 months ago 15
Ruby Question

Ruby how to override ruby sort_by

I'm trying to create a method that uses the functionality of Array's

sort_by
method.

Imagine I have this data

data_array = [{project: 'proj', version: '1.1'}, {project: 'proj2', version: '1.11'}, {project: 'proj3', version: '1.2'}]


I want to be able to call the method like this:

data_array.natural_sort_by{|x| x['version'] }


The actual call that happens would achieve something like this:

data_array.sort_by{|x| MyModule.naturalize_str(x['version']) }


Heres my current unworking code:

Array.module_eval do
def natural_sort_by(&block)
sort_by{|x| Rearmed.naturalize_str(eval(block))}
end
end


I'm not quite sure how to achieve this.

Answer
class Array
  def natural_sort_by
    sort_by{|x| MyModule.naturalize_str(yield(x))}
  end
end

or

class Array
  def natural_sort_by &block
    sort_by{|x| MyModule.naturalize_str(block.call(x))}
  end
end
Comments