我有一个值“狗”和一个数组[“猫”、“狗”、“鸟”]。
如何在不循环的情况下检查数组中是否存在它?是否有一种简单的方法来检查该值是否存在?
我有一个值“狗”和一个数组[“猫”、“狗”、“鸟”]。
如何在不循环的情况下检查数组中是否存在它?是否有一种简单的方法来检查该值是否存在?
当前回答
您正在查找包含项?:
>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true
其他回答
array = [ 'Cat', 'Dog', 'Bird' ]
array.include?("Dog")
如果要在MiniTest单元测试中执行此操作,可以使用assert_includes。例子:
pets = ['Cat', 'Dog', 'Bird']
assert_includes(pets, 'Dog') # -> passes
assert_includes(pets, 'Zebra') # -> fails
Try
['Cat', 'Dog', 'Bird'].include?('Dog')
如果你不想使用include?您可以首先将元素包装在数组中,然后检查包装的元素是否等于数组和包装的元素的交集。这将返回一个基于相等的布尔值。
def in_array?(array, item)
item = [item] unless item.is_a?(Array)
item == array & item
end
还有另一种方法。
假设数组是[:edit,:update,:create,:show],那么可能就是七宗致命/宁静的罪。
还有一个想法,就是从某个字符串中提取一个有效的动作:
"my brother would like me to update his profile"
然后:
[ :edit, :update, :create, :show ].select{|v| v if "my brother would like me to update his profile".downcase =~ /[,|.| |]#{v.to_s}[,|.| |]/}