top | item 44255683

(no title)

ht85 | 8 months ago

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

discuss

order

onli|8 months ago

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".

sathishmanohar|8 months ago

The same can be achieved with

  [maximum_number_of_students - students.size, 0].max

ricardobeat|8 months ago

I don’t get how this works. Won’t the spaceship operator always return 1, 0, -1?

onli|8 months ago

Yes. And then clamp(0..) removes the -1, maps it to a 0. Why you'd want that? No idea.