javascript Ruby 中的 indexOf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12616878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:40:30  来源:igfitidea点击:

indexOf in Ruby

javascriptrubyarrays

提问by Hymanie Chan

Just wondering is there the same method for an Array object similar to indexOf in JavaScript?

只是想知道对于类似于 JavaScript 中的 indexOf 的 Array 对象是否有相同的方法?

For example:

例如:

arr = %w{'a', 'b', 'c'}
c = 'c'
if (arr.indexOf(c) != -1)
// do some stuff
else
// don't do some stuff

回答by xdazz

It is the .indexmethod of Array.

它是.indexArray的方法。

http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-index

http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-index

In ruby, only falseand nilare considered as false value, so you could just do:

在 ruby​​ 中, onlyfalsenil被认为是假值,所以你可以这样做:

arr = %w{a, b, c}
c = 'c'
if arr.index c
  # do something
else 
  # do something else
end 

回答by Sébastien Le Callonnec

If you want to check the presence of an element in the array, you can use include?:

如果要检查数组中是否存在某个元素,可以使用include?

if arr.include?(c)
  # do stuff
else 
  # don't
end

回答by Hck

Use Array#index for this:

为此使用 Array#index:

c = 'c'
%w{a b c}.index(c)

回答by sawa

if arr.last == c
  # do some stuff
else
  # don't do some stuff
end