Ruby select array method

In ruby programming language, select() method of array are use to get specific element in array. This method are based on block return value. Syntax of this method as follows.

Syntax :
Array.select {|item| block} → return new array
Array.select → Enumerator when no block

When conditional block is return a true value, Then element is part of resultant array. When they return always false then this method returns empty array. Method block of this statement are optional, When that is not provide a Enumerator. For example.

Ruby select method example

select() method is based on block return boolean value, Inside the block we can define multiple statements last statement are used to returning value. Let see an basic example.

# Our array
arr  = [3,-2,-4,5,8,9,-6,1]

# Select operation
negative  = arr.select{|v| v < 0}
positive  =  arr.select{|v| v > 0}
even  =  arr.select{|v| v % 2 == 0}
odd  =  arr.select{|v| v % 2 != 0}

# Display array
print(" Array : ",arr)

# Display result
print("\n negative : ",negative)
print("\n positive : ",positive)
print("\n even : ",even)
print("\n odd : ",odd)
Ruby select method example 1
 Array : [3, -2, -4, 5, 8, 9, -6, 1]
 negative : [-2, -4, -6]
 positive : [3, 5, 8, 9, 1]
 even : [-2, -4, 8, -6]
 odd : [3, 5, 9, 1]

We can use multiple statements inside the block. lets see an example to understand.

# Our array
arr  = [3,-2,-4,5,8,9,4,-6,1]

# Select operation
data  = arr.select{
  |v| 
  if(v >= 2 && v <= 5)
     true # return value
  else
    false # return value
  end
}


# Display array
print(" Array : ",arr)

# Display result
print("\n data : ",data)
 Array : [3, -2, -4, 5, 8, 9, 4, -6, 1]
 data : [3, 5, 4]

When block are missing then its return an Enumerator.

 # Our array
arr  = [3,-2,-4,5,8,9,-6,1]

# Select operation
v  =  arr.select

# Display array
print(" Array : ",arr)

# Display result
print("\n v : ",v)
Ruby select method example 2


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved