Reputation: 1686
What is the Ruby way to assign a variable a to another variable b if a is superior to b ?
I have three possibilities so far :
if a > b then a = b end
a = b if a > b
a = a > b ? b : a
More broadly, is there a way to set an upper limit to a variable ? e.g: if I try to set a = 50 and a has an upper limit of 25, a will be equal to 25 after assignment.
Upvotes: 1
Views: 894
Reputation: 4218
How about a > b && a = b
where b
is that upper limit.
b = 25
a = 25
a > b && a = b #> false; a = 25
a = 26
a > b && a = b #> true; a = 25
Upvotes: 2
Reputation: 35788
All three options work, it's just a question of style.
I'd go with number 2. It most clearly communicates your intent, while avoiding extraneous keywords (number 1) or excessively terse one liners (number 3).
In answer to your more general question, there is no way to override variable assignment in Ruby. You can override assignment to instance variables using setter methods though. If you just want to do it afterwords, the code from your question is sufficient:
a = something
a = 25 if a > 25
Upvotes: 5
Reputation: 694
Try: b = a > b ? a : b
It's the same as writing:
if a > b
b = a
else
b = b
end
Upvotes: 1
Reputation: 11275
So you ask for the upper limit:
UPPER_LIMIT = 25
b = 100
a = [b, UPPER_LIMIT].min
a
will always smaller or equal to 25
.
Upvotes: 5