Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby element present in array or not [duplicate]

Possible Duplicate:
how to check if my array includes an object - rails

I have array

array['one', 'two', 'three'] 

How i find that 'two' element present in array.

Is any method in ruby which can find this?

Thanks

like image 804
Sachin R Avatar asked Aug 14 '10 05:08

Sachin R


People also ask

How do you check if there are duplicates in an array Ruby?

select { array. count } is a nested loop, you're doing an O(n^2) complex algorithm for something which can be done in O(n). You're right, to solve this Skizit's question we can use in O(n); but in order to find out which elements are duplicated an O(n^2) algo is the only way I can think of so far.

How do you check if a value is present in an array in Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.

What does .first do in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

What does .last do in Ruby?

The . last property of an array in Ruby returns the last element of the array.


1 Answers

array.include?('two') returns true or false

like image 101
zetetic Avatar answered Oct 05 '22 23:10

zetetic