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]
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With