检查数字是否在范围内的一个语句

huangapple go评论50阅读模式
英文:

Check if numeral within bounds in one statement

问题

# 不是有效的 Ruby 语法,有其他方法吗?
a < x && x < b
英文:

Is there a way to check if a number x is greater than a number a and less than a number b, without specifying x twice?

I can do this:

x = 4
a = 1
b = 10
x &gt; a &amp;&amp; x &lt; b

...but is there a way to do something like this:

# not valid ruby, is there another way?
a &lt; x &lt; b

答案1

得分: 1

Tested this to work for x being an Integer and a Float.

(a..b).include? x

Edit:
As @spickermann pointed out in comments the original question excludes the beginning and the end of the interval.

To exclude the end is easy, this is what ... is for. Therefore

(a...b).include? x  # is the same as `a &lt;= x &amp;&amp; x &lt; b`

To exclude the start of the interval is not that easy. One could use next_float:

(a.to_f.next_float...b).include? x

However even the (a...b) is something I would not use because it is not so common literal and in my opinion decreases readability of the code. With a.to_f.next_float we are making some really awkward code that may work for Integers and Floats but I would be afraid of other Numeric data types.

Unless someone brings completely different approach I would stick with x &gt; a &amp;&amp; x &lt; b

英文:

This does not answer the question exactly, please read the Edit part of the answer.

Tested this to work for x being an Integer and a Float.

(a..b).include? x

Edit:
As @spickermann pointed out in comments the original question excludes the beginning and the end of the interval.

To exclude the end is easy, this is what ... is for. Therefore

(a...b).include? x  # is the same as `a &lt;= x &amp;&amp; x &lt; b`

To exclude the start of the interval is not that easy. One could use next_float:

(a.to_f.next_float...b).include? x

However even the (a...b) is something I would not use because it is not so common literal and in my opinion decreases readability of the code. With a.to_f.next_float we are making some really awkward code that may work for Integers and Floats but I would be afraid of other Numeric data types.

Unless someone brings completely different approach I would stick with x &gt; a &amp;&amp; x &lt; b

huangapple
  • 本文由 发表于 2023年2月18日 00:53:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487128.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定