简单的Ruby’或’问题

在控制台中:

@user.user_type = "hello" @user.user_type == "hello" true @user.user_type == ("hello" || "goodbye") false 

如何编写最后一个语句,以便检查@user.user_type是否包含在两个字符串之一中?

 ["hello", "goodbye"].include? @user.user_type 

Enumerable#include? 这是一种惯用而简单的方法,但作为旁注,让我向您展示一个非常简单的扩展(我想)会取悦Python粉丝:

 class Object def in?(enumerable) enumerable.include?(self) end end 2.in? [1, 2, 3] # true "bye".in? ["hello", "world"] # false 

有时候(实际上大部分时间),从语义上来说,询问一个对象是否在一个集合中而不是相反的方式更合适。 现在您的代码看起来像:

 @user.user_type.in? ["hello", "goodbye"] 

顺便说一句,我想你想写的是:

 @user.user_type == "hello" || @user.user_type == "goodbye" 

但是我们程序员本质上是懒惰的,所以最好使用Enumerable#include? 和朋友。