Search code examples
rubyvariable-assignmentmaxassignment-operatormin

Ruby min max assignment operators


When programming ruby I always find myself doing this:

a = [a, b].min

This means compare a and b and store the smallest value in a. I don't like writing the code above as I have to write a twice.

I know that some non-standard dialects of C++ had an operator which did exactly this

a <?= b

Which I find very convenient. But I'm not really interested in the operator as much as I'm in the feature of avoiding repetition. I would also be happy if I could write

a.keep_max(b)

a can be a quite long variable, like my_array[indice1][indice2], and you don't want to write that twice.

I did alot of googling on this and found no result, hopefully this question will pop up and be useful for others aswell.

So, is there any non-repeitive way to express what I want in ruby?


Solution

  • What you would like to do is in fact not possible in ruby (see this question). I think the best you can do is

    def max(*args)
      args.max
    end
    
    a = max a, b