IndexOf in Ruby

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

For instance:

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

This is the .index array method.

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

In ruby, only false and nil are considered false, so you can simply do:

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

If you want to check for an element in an array, can you use include? :

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

Use the Array # parameter for this:

 c = 'c' %w{abc}.index(c) 
+1
source
 if arr.last == c # do some stuff else # don't do some stuff end 
0
source

Source: https://habr.com/ru/post/1436540/


All Articles