New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement '<=>' for Bool #5162

Closed
rdp opened this Issue Oct 21, 2017 · 6 comments

Comments

Projects
None yet
4 participants
@rdp
Contributor

rdp commented Oct 21, 2017

I sometimes wish to sort by boolean, simplified example:

a = [1,2,3]
a.sort_by{|n| n == 3}

today it yields: undefined method '<=>' for Bool

Consider this a feature request. Thanks!

@mvlootman

This comment has been minimized.

mvlootman commented Oct 21, 2017

Just wondering what the use case for this would be?
Would the partition method be a way to separate the items based on the boolean expression?

@Sija

This comment has been minimized.

Contributor

Sija commented Oct 21, 2017

@rdp Boolean values have no natural ordering.
I'd advise using Enumerable#partition instead, as mentioned by @mvlootman.

You can monkey-patch Bool urself though (don't):

struct Bool
  def <=>(other : Bool)
    self == other ? 0 : -1
  end
end

PS. See similar question at SO.

@rdp

This comment has been minimized.

Contributor

rdp commented Oct 21, 2017

Nice! Yeah partition would work, in my case I just want to send elements with a certain attribute to the "end" or "beginning" of an array. @Sija thanks, yeah having it in core would be kind... :)

@RX14

This comment has been minimized.

Member

RX14 commented Oct 21, 2017

Boolean doesn't have a natural ordering... Is true less than false? No, it's not. I think this is a terrible idea.

You're using sort_by anyway, you can just use sort_by { |n| n == 3 ? -1 : 1 } or the other way around if you want the other sort direction.

@RX14 RX14 closed this Oct 21, 2017

@rdp

This comment has been minimized.

Contributor

rdp commented Nov 5, 2017

It's not hard to imagine "some arbitrary order" (true == 1, false == 1) by default and just let that (thus avoiding the ternary's) but if it's too contentious hopefully people will be able to find this and just use Sija's work around now. Thanks all!

@rdp

This comment has been minimized.

Contributor

rdp commented Oct 18, 2018

OK I had some difficulty getting the snippet above to work, but this seems to do the trick, instead of just clumping "trues and falses together" regardless of which one is which:

struct Bool
  def <=>(other : Bool)
    if self == other
      return 0
    elsif self
      return 1
    else
      return -1
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment