测试变量是否等于两个值之一 [英] Test whether a variable equals either one of two values
问题描述
我想测试 a
是否等于 1 或 2
I want to test whether a
equals 1 or 2
我能做到
a == 1 || a == 2
但这需要重复a
(这对于较长的变量会很烦人)
but this requires repeating a
(which would be annoying for longer variables)
我想做a == (1 || 2)
之类的事情,但显然这行不通
I'd like to do something like a == (1 || 2)
, but obviously this won't work
我可以做 [1, 2].include?(a)
,这还不错,但让我觉得有点难以阅读
I could do [1, 2].include?(a)
, which is not bad, but strikes me as a bit harder to read
只是想知道如何用惯用的 ruby 做到这一点
Just wondering how do to this with idiomatic ruby
推荐答案
您的第一个方法是惯用的 Ruby.不幸的是,Ruby 没有与 Python 的 a in [1,2]
等效,我认为它会更好.你的 [1,2].include?a
是最接近的选择,我认为它与最自然的方式有点倒退.
Your first method is idiomatic Ruby. Unfortunately Ruby doesn't have an equivalent of Python's a in [1,2]
, which I think would be nicer. Your [1,2].include? a
is the nearest alternative, and I think it's a little backwards from the most natural way.
当然,如果你经常使用它,你可以这样做:
Of course, if you use this a lot, you could do this:
class Object
def member_of? container
container.include? self
end
end
然后你可以做a.member_of?[1, 2]
.
这篇关于测试变量是否等于两个值之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!