Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Detect method

Tags:

ruby

detect

Select makes sense. But can someone explain .detect to me? I don't understand these data.

>> [1,2,3,4,5,6,7].detect { |x| x.between?(3,4) } => 3 >> [1,2,3,4,5,6,7].detect { |x| x.between?(3,6) } => 3 >> [1,2,3,4,5,6,7].detect { |x| x.between?(3,7) } => 3 >> [1,2,3,4,5,6,7].detect { |x| x.between?(2,7) } => 2 >> [1,2,3,4,5,6,7].detect { |x| x.between?(1,7) } => 1 >> [1,2,3,4,5,6,7].detect { |x| x.between?(6,7) } => 6 >> [1,2,3,4,5,6,7].select { |x| x.between?(6,7) } => [6, 7] >> [1,2,3,4,5,6,7].select { |x| x.between?(1,7) } => [1, 2, 3, 4, 5, 6, 7] 
like image 932
JZ. Avatar asked Jun 07 '10 02:06

JZ.


People also ask

How do you use the Find method in Ruby?

The find method locates and returns the first element in the array that matches a condition you specify. find executes the block you provide for each element in the array. If the last expression in the block evaluates to true , the find method returns the value and stops iterating.

What does .select do in Ruby?

Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.

What is .all in Ruby?

The all?() of enumerable is an inbuilt method in Ruby returns a boolean value true if all the objects in the enumerable satisfies the given condition, else it returns false. If a pattern is given, it compares with the pattern, and returns true if all of them are equal to the given pattern, else it returns false.

What is .collect in Ruby?

The collect() of enumerable is an inbuilt method in Ruby returns a new array with the results of running block once for every element in enum. The object is repeated every time for each enum. In case no object is given, it return nil for each enum.


1 Answers

Detect returns the first item in the list for which the block returns TRUE. Your first example:

>> [1,2,3,4,5,6,7].detect { |x| x.between?(3,4) } => 3 

Returns 3 because that is the first item in the list that returns TRUE for the expression x.between?(3,4).

detect stops iterating after the condition returns true for the first time. select will iterate until the end of the input list is reached and returns all of the items where the block returned true.

like image 129
ryeguy Avatar answered Oct 12 '22 13:10

ryeguy