标准的写法似乎是array.include?(object)
,但我发现与object.in(array)相比,这种方式阅读和理解起来更加困难。Ruby中是否有类似的方法?
我刚刚遇到的例子是(user_role是一个字符串,allowed_user_roles是一个字符串数组):
allowed_user_roles.include?(user_role)
我知道这可能是个人偏好,但我发现这样更容易阅读和理解。
user_role.in(allowed_user_roles)
这个功能不是 Ruby 核心的一部分,但是它被添加到了 ActiveSupport 核心扩展 中。如果你使用 Rails,你可以使用这个功能:
1.in?([1,2]) # => true
"lo".in?("hello") # => true
25.in?(30..50) # => false
1.in?(1) # => ArgumentError
如果要在Rails之外使用它,您需要安装active_support
gem,然后需要引入 active_support/core_ext/object/inclusion
:
# Gemfile
gem 'active_support'
# code
require 'active_support/core_ext/object/inclusion'
class Object
def in?(collection)
raise ArgumentError unless collection.respond_to?(:include?)
collection.include?(self)
end
end
那么任何继承自Object的东西(几乎所有东西)都将拥有一个#in?
方法。
5.in?(0..10)
=> true
'carrot'.in?(['potato', 'carrot', 'lettuce'])
=> true
ary.index(obj)
而不是obj.index_within(ary)
。或者说'ruby'.start_with?('ru')
而不是'ru'.prefix_of?('ruby')
。在你的例子中,数组可能包含另一个具有相同字符的字符串,即不是同一个对象。所以你在问这个字符串:“嘿,字符串,这个数组里有没有另一个看起来和你一模一样的字符串?”而不是“嘿,数组,你是否包含一个等于这个的字符串?”对我来说,前者似乎有点奇怪。 - Stefanif str.in? names then...
:) - mrzasaif str.in? name then...
。 - Cary Swovelandneedle.in?(haystack)
这样的语法暗示着needle知道它是否在haystack中。它只需要回答“是”或“否”,也就是说,我期望得到一个即时响应。而haystack.include?(needle)
听起来就像一项繁琐的任务。 如果没有接收器,则情况会有所不同。如果in?
是一个运算符,那么obj in? collection
(没有点号,不指向obj
)将成为一个更普遍的问题,并且可以作为collection.include?(obj)
的语法糖。如你所说,这可能只是个人偏好。 - Stefan[1,2].in?([1,3,4])
应该返回什么?),我理解@Stefan的想法。 - Felix