testing一个variables是否等于两个值之一
我想testinga等于1 还是等于2
我可以
a == 1 || a == 2
但是这需要重复a (这会对较长的variables产生干扰)
我想要做a == (1 || 2) ,但显然这是行不通的
我可以做[1, 2].include?(a) ,这并不坏,但是让我觉得有点难读
只是想知道如何做到与惯用的ruby
你的第一个方法是惯用的Ruby。 不幸的是,Ruby并没有a in [1,2]的Python a in [1,2] ,我认为它会更好。 你的[1,2].include? a [1,2].include? a是最接近的select,我认为这是最自然的方式。
当然,如果你使用这个很多,你可以这样做:
class Object def member_of? container container.include? self end end
然后你可以做a.member_of? [1, 2] a.member_of? [1, 2] 。
我不知道你使用的是什么环境,但是如果它适合switch语句,你可以这样做:
a = 1 case a when 1, 2 puts a end
一些其他的好处是,当使用case ===运算符时,所以如果你想,你可以重写该方法的不同行为。 另一个是,如果符合你的用例,你也可以使用范围:
when 1..5, 7, 10
一种方法是请求“Matz”将这个function添加到Ruby规范中。
if input == ("quit","exit","close","cancel") then #quit the program end
但是,case-when声明已经可以让你做到这一点:
case input when "quit","exit","close","cancel" then #quit the program end
当写在这样的一条线上,它的行为,几乎看起来像一个if语句。 底部的例子是一个很好的临时替代顶部的例子? 你是法官。
首先把这个地方:
class Either < Array def ==(other) self.include? other end end def either(*these) Either[*these] end
那么,那么:
if (either 1, 2) == a puts "(i'm just having fun)" end
a.to_s()=~/^(1|2)$/
你可以使用像十字路口
([a] & [1,2]).present?
另一种方法。
也许我在这里很厚,但在我看来:
(1..2) === a
…作品。