【发布时间】:2011-05-24 04:29:30
【问题描述】:
在控制台中:
@user.user_type = "hello"
@user.user_type == "hello"
true
@user.user_type == ("hello" || "goodbye")
false
如何编写最后一条语句,以便检查@user.user_type 是否包含在两个字符串之一中?
【问题讨论】:
标签: ruby-on-rails ruby conditional
在控制台中:
@user.user_type = "hello"
@user.user_type == "hello"
true
@user.user_type == ("hello" || "goodbye")
false
如何编写最后一条语句,以便检查@user.user_type 是否包含在两个字符串之一中?
【问题讨论】:
标签: ruby-on-rails ruby conditional
["hello", "goodbye"].include? @user.user_type
【讨论】:
include? 工作正常。 +1!
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? 和朋友。
【讨论】: