Sort Objects by Boolean values in Ruby

My apologies if this has been answered before or is obvious...did some searching here and on the Goog and couldn't find an answer.

I'm looking to sort an array of Providers by price and whether they are a preferred_provider? (true or false)

For instance in array p of Providers...

p1.price == 1, p1.preferred_provider? == false p2.price == 2, p2.preferred_provider? == true p2.price == 3, p3.preferred_provider? == true

I would like to p.sort_by and get:

[p2 p3 p1]


p.sort_by {|x| x.preferred_provider?, x.price }

does not work and gets...

undefined method `<=>' for false:FalseClass

Any suggestions on better ways to approach this problem?

-------------Problems Reply------------

Most languages provide sort functions that accept comparators for this sort of thing. In Ruby, this is just array.sort:

p.sort {|a, b| if (a.preferred_provider? == b.preferred_provider?
then a.price <=> b.price
elsif a.preferred_provider?
else -1

You could define a <=> on the Provider class to do what you want, and then sort using the Array.sort method (rather than Enumerable.sort_by). Here's a definition of <=> that I whipped up:

class Provider
def <=>(other)
if preferred_provider?
if other.preferred_provider?
@price <=> other.price
if other.preferred_provider?
@price <=> other.price

Then, if you have your array p, you could just do p_sorted = p.sort.

(Note that I haven't tested this code, so there may be a few errors, but I think it serves to demonstrate the idea.)

Category:ruby on rails Views:0 Time:2009-05-24

Related post

  • Sorting by a value in an object in an array in Ruby 2011-04-19

    I have a bunch of objects in an array and would like to sort by a value that each object has. The attribute in question in each object is a numeric value. For example: [[1, ..bunch of other stuff],[5, ""],[12, ""],[3, ""],] would become: [[1, ..bunch

  • Sorting objects in an array by a field value in JavaScript 2009-07-15

    Say I have an array of JavaScript objects: var objs = [ { first_nom: 'Lazslo', last_nom: 'Jamf' }, { first_nom: 'Pig', last_nom: 'Bodine' }, { first_nom: 'Pirate', last_nom: 'Prentice' } ]; How can I sort them by the value of last_nom in JavaScript?

  • Bubble sort object by any property? 2012-03-26

    I am using a bubble sort function to sort objects by their properties. Unfortunately I have had to write one function for every property. Is there any way to generalize the functions below. Instead of writing SortArticlesByVolume(a) SortArticlesByLen

  • Sorting objects based on Double values? 2009-08-04

    Sorting objects is simple enough by mixing in Ordered and providing a compare() function, as shown here. But what if your sorting value is a Double instead of an Int? def compare(that: MyClass) = this.x - that.x where x is a Double will lead to a com

  • Arrays.sort(Object[] a) - how is it implemented? 2010-02-07

    Are there any resources on how the mergeSort used by Arrays.sort(Object[] a) is implemented? While it is documented quite good, I have a hard time understanding it (especially why the src and dest are are switched when mergeSort() get's recursively c

  • Sorting objects in Python 2010-04-30

    I want to sort objects using by one of their attributes. As of now, I am doing it in the following way USpeople.sort(key=lambda person: person.utility[chosenCar],reverse=True) This works fine, but I have read that using operator.attrgetter() might be

  • C#, sorting objects in list by Name 2010-08-11

    how could i sort objects in list by their name? Example: mapPart_1_0 mapPart_1_2 mapPart_1_4 mapPart_1_6 mapPart_1_8 mapPart_1_10 mapPart_1_12 mapPart_1_24 mapPart_2_1 mapPart_2_11 Big list continues... (somewhere in that list are missing that aper i

  • Why does java.util.Arrays.sort(Object[]) use 2 kinds of sorting algorithms? 2010-08-25

    I found that java.util.Arrays.sort(Object[]) use 2 kinds of sorting algorithms(in JDK 1.6). pseudocode: if(array.length<7) insertionSort(array); else mergeSort(array); Why does it need 2 kinds of sorting here? for efficiency? --------------Solutio

  • Sorting objects with Thrust CUDA 2011-03-12

    Is it possible to sort objects using the Thrust library? I have the following struct: struct OB{ int N; Cls *C; //CLS is another struct. } Is it possible to use thrust in order to sort an array of OB according to N? Can you provide a simple example o

  • How to sort an array of floats in Ruby? 2011-03-28

    Just wondering how to sort an array of floats in Ruby, since "sort" and "sort!" only work for integer arrays. --------------Solutions------------- Arrays of floats can certainly be sorted: >> [6.2, 5.8, 1.1, 4.9, 13.4].sort => [1.1, 4.9, 5.8

  • Powershell Sort-Object by [DateTime]::ParseExact 2011-04-28

    I'm trying to sort the lines returned by a console program by date, using PowerShell. The dates are formated in MM/dd/yyyy format, so they have to be converted to DateTime objects to be in a sortable format. To parse the dates, I use: $dates = %{ "10

  • Chrome sorts objects by key 2011-05-29

    Possible Duplicate: Chrome and probably Opera sort object properties automatically I have a very simple code: var obj = {3:'a',2:'b',1:'c'}; console.log(obj); In Firefox 4.0.1 it returns: Object { 3="a", 2="b", 1="c"} In Chrome 11.0.696.71 it returns

  • Convert Object to Boolean[][] 2011-11-18

    How I can convert an Object to Array of Boolean Arrays? Boolean[][] mass; mass = (Boolean[5][5])Object; --------------Solutions------------- Is this answer to your question: Boolean[][] tst = new Boolean[5][5]; Object obj = tst; Boolean[][] mass; mas

  • String object to Boolean 2012-04-25

    When i tried to convert a String Object to boolean, the result is different. String strFlag="true"; boolean boolFlag = Boolean.getBoolean(strFlag); boolFlag ends up having a false value. --------------Solutions------------- Use Boolean.valueOf(String

  • whenever i start windows i get this message ''unable to cast object system.boolean to system.string " how to remove this 2013-04-17

    whenever i start windows i get this message ''unable to cast object system.boolean to system.string " how to remove this --------------Solutions------------- Hi Indu, Thank you for choosing Microsoft Community! I understand that, you are receiving er

  • sort object properties and JSON.stringify 2013-04-23

    My application has a large array of objects, which I stringify and save to disk. Unfortuately, when the objects in the array are manipulated, and sometimes replaced, the properties on the objects are listed in different orders (their creation order?)

  • Sorting an array of arrays in Ruby 2009-07-28

    I have an array of arrays like so: irb(main):028:0> device_array => [["name1", "type1", ["A", "N", "N"], ["Attribute", "device_attribute"], 9], ["name2","type2", ["A", "N", "N"], ["Attribute", "device_attribute"], 7]] I would like to sort the e

  • Accessing member variables of other object of same class in Ruby 2009-09-18

    In Java I can do: public boolean equals(Object other) { return this.aPrivateVariable == ((MyClass)other).aPrivateVariable; } This allows me to define equality without breaking the encapsulation of my class. How can I do the same in Ruby? Thanks. ----

  • Passing boolean parameter in ruby 2012-02-10

    I am wondering how do I pass a false value to my ruby script. If I invoke: ruby myscript.rb false and then in my script if I say:*ARGV) or[0]) basically a string with value "false" gets passed. Clearly if I say if(ARGV

Copyright (C), All Rights Reserved.

processed in 0.140 (s). 11 q(s)