Hacker News new | ask | show | jobs
by ht85 365 days ago

    (maximum_number_of_students <=> students.size).clamp(0..)
Holy... Is this better or worse than write-once perl regexes?
3 comments

I started writing a comment wanting to defend it, because the expressions themselves are not that unreadable. <=> is a comparator (and used in many languages), clamp sets min and max sizes (and that can be guessed from the english meaning of the word), and 0.. is a range that goes from 0 to infinity (admittedly not that common an expression, but completely logical and intuitive way to express a range once you understood once that it is about ranges).

But then I realized that's nonsensical, and not what the code is supposed to do given the usage in the template. I assume something got mangled there when changing the code for the blog post.

Or I'm just understanding the ruby code wrong despite checking just now in irb, in that case that's a point for the intention of your comment, and a vote for "worse".

The same can be achieved with

  [maximum_number_of_students - students.size, 0].max
I don’t get how this works. Won’t the spaceship operator always return 1, 0, -1?
Yes. And then clamp(0..) removes the -1, maps it to a 0. Why you'd want that? No idea.
so this just says if we have free places or not? students.size < maximum_number_of_students
It gives the number of free places, hinted by the method name `available_places`

Needlessly ugly way to write it imo though

But it doesn't. The code will only ever output 0 or 1. With a regular <=> operator at least.
yeah, so basically 1 we have available places, 0 we do not.
I think it probably made sense to the author because they've used all three (-1,0,1) for other examples, and would've been fine until separated out to a method reused to show the actual number.

I think they tried to be a bit too clever, basically.