英文:
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 > a && x < b
...but is there a way to do something like this:
# not valid ruby, is there another way?
a < x < 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 <= x && x < 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 > a && x < 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 <= x && x < 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 > a && x < b
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论