Matt Elhotiby
Matt Elhotiby

Reputation: 44086

How do i find if element is not in a ruby array?

Ok so i have this array

 array
 => [1620, 3093] 

and I have a integer

 num
 => 1620 

is there an easy way to see if there is another number in the array that is not num

so for example

is there another number in the array that doesnt match num. So for the above example i would return true but if array was [1620, 1620] then i would return false

Upvotes: 0

Views: 90

Answers (4)

ddb
ddb

Reputation: 1406

Join the sorted array with a separator and find if there is a match with 2 adjacent numbers.

array.sort.join(",").include?("#{num},#{num}")

Upvotes: 1

Aditya Sanghi
Aditya Sanghi

Reputation: 13433

arr.any?{|x| x != num }

The above should work fine, is readable and efficient too!

Upvotes: 6

Rob d'Apice
Rob d'Apice

Reputation: 2416

array.select{|array_num| array_num != num}.length > 0

EDIT: or even cleaner:

(array - [num]).empty?

Upvotes: 2

deefour
deefour

Reputation: 35370

array.reject{ |a| a == num }.size > 0

Upvotes: 2

Related Questions