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
indexOf in Ruby
提问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 .index
method of Array.
它是.index
Array的方法。
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 false
and nil
are considered as false value, so you could just do:
在 ruby 中, onlyfalse
和nil
被认为是假值,所以你可以这样做:
arr = %w{a, b, c}
c = 'c'
if arr.index c
# do something
else
# do something else
end
回答by Sébastien Le Callonnec
回答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