我有一个值“狗”和一个数组[“猫”、“狗”、“鸟”]。

如何在不循环的情况下检查数组中是否存在它?是否有一种简单的方法来检查该值是否存在?


当前回答

在任何数组中查找元素有多种方法,但最简单的方法是“in?”方法

example:
arr = [1,2,3,4]
number = 1
puts "yes #{number} is present in arr" if number.in? arr

其他回答

检查是否存在

使用include?

例子:

arr = [1, 2, 3]
arr.include?(1) -> true
arr.include?(4) -> false

支票不存在

使用排除?

例子:

arr = %w(vietnam china japan)
arr.exclude?('usa') -> true
arr.exclude?('china') -> false

这不仅会告诉你它存在,还会告诉你它出现的次数:

 a = ['Cat', 'Dog', 'Bird']
 a.count("Dog")
 #=> 1

在任何数组中查找元素有多种方法,但最简单的方法是“in?”方法

example:
arr = [1,2,3,4]
number = 1
puts "yes #{number} is present in arr" if number.in? arr

还有另一种方法。

假设数组是[: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}[,|.| |]/}

这是另一种方法:使用Array#索引方法。

它返回数组中元素第一次出现的索引。

例如:

a = ['cat','dog','horse']
if a.index('dog')
    puts "dog exists in the array"
end

index()也可以采用一个块:

例如:

a = ['cat','dog','horse']
puts a.index {|x| x.match /o/}

这将返回数组中包含字母“o”的第一个单词的索引。