所以写这个的标准方法似乎是array.include?(object)。但是,与object.in(array)相比,我发现很难快速阅读和理解。红宝石中有这样的东西吗?
我刚刚再次遇到的示例是(user_role是一个字符串,而allowed_user_roles是一个字符串数组):
allowed_user_roles.include?(user_role)
Run Code Online (Sandbox Code Playgroud)
我知道它可能是个人喜好,但是我发现它很容易阅读和理解。
user_role.in(allowed_user_roles)
Run Code Online (Sandbox Code Playgroud)
它不在Ruby核心中,而是在ActiveSupport核心扩展中添加的。如果您使用Rails,则可以使用:
1.in?([1,2]) # => true
"lo".in?("hello") # => true
25.in?(30..50) # => false
1.in?(1) # => ArgumentError
Run Code Online (Sandbox Code Playgroud)
要在Rails之外使用它,您需要安装active_supportgem,然后要求active_support/core_ext/object/inclusion:
# Gemfile
gem 'active_support'
# code
require 'active_support/core_ext/object/inclusion'
Run Code Online (Sandbox Code Playgroud)