« Sequence Mappability & Alignability | Genometastasis » |

## Ruby Sorting

Sorting (elements in an array) is a very common tasks in many scripts. A lot of research has gone into finding the most efficient way to sort.

In Ruby the "sort" function performs a standard comparison accoring to the data type inspected, but as in most other languages you can define any specific orders.

open_orders.sort

is equivalent to

open_orders.sort { |x, y| x <=> y }

The sort algorithm will assume that this comparison function/block will return a value accoring to the following logic (like the comparison operators):

return -1 if x < y return 0 if x = y return 1 if x > y

So using this logic I can define a specific custom function to to compare the elements that need sorting and call it in the sort function afterwards. In my simple example I need to sort order numbers by two criteria: by a string first ("UK" before "ORD") and by ascending numbers afterwards.

Code

`def custom_order_sorting(x_ord,y_ord)` | |

` if(x_ord.match('UK') ` | |

` and y_ord.match('ORD'))` | |

` #use UK first` | |

` return -1` | |

` elsif(x_ord.match('ORD') ` | |

` and y_ord.match('UK'))` | |

` #use UK first` | |

` return 1` | |

` else` | |

` #use smaller number first` | |

` x_num = x_ord.match('\w(\d+)$')[1]` | |

` y_num = y_ord.match('\w(\d+)$')[1]` | |

` return x_num <=> y_num` | |

` end` | |

` end` | |

` ` | |

`open_orders.sort!{|x,y| custom_order_sorting(x,y)}` |

Source: stackoverflow.com

This entry was posted on 09 May 2012 at 13:46 by felix and is filed under Ruby/Rails, Bioinformatics.