What is the set.divide() function in Ruby?

A built-in Ruby function called divide() returns a set of subsets. It takes a condition specified by a blockIn the context of Ruby programming, a block is a chunk of code enclosed within either braces {}. Blocks are often used in conjunction with methods to provide additional functionality or customize behavior.. The blocks determine the division based on the provided standards. If an element doesn’t meet the condition, it becomes a single-element subset. Ruby’s set class provides a useful way for splitting sets into subsets according to user-defined criteria. Users can divide the set according to arbitrary criteria by utilizing blocks, allowing for flexible data processing and analysis.

Syntax

The following is the syntax of the built-in Ruby function divide():

s1.divide { |i, j| condition }

The condition under which the set is to be subdivided into a set of subsets is taken by the function divide().The variables i and j are block parameters used in the block passed to the set.divide() method.

Return value

It creates a new set by duplicating the original set and removes every element that appears in the given enumerable objectThe result of applying the condition..

Code example

Let’s explore how the set.divide() function works in Ruby with the help of a code example:

# Requires the set class
require "set"
# Creates a set
s1 = Set.new([8, 5, 4, 11, 14, 7, 20, 17])
puts "Original Set:"
puts s1.to_a
# Divides the set into subsets based on a condition
result = s1.divide { |i, j| (i - j).abs == 2 }
puts "\nDivided Sets:"
result.each_with_index do |subset, index|
puts "Subset #{index + 1}: #{subset.to_a}"
end

Explanation

  • Line 2: We use require to include the set class in our program.

  • Line 5: We create a set s1 containing various numbers.

  • Line 8: We print the original set to the console using the to_a method, which converts the set to an array for display.

  • Line 11: We use the set.divide() method to divide the set into subsets based on a condition provided in the block. In this example, the condition is that the absolute difference between elements in a subset should be 2.

  • Lines 13–16: We print the divided sets. Each subset is printed with a label indicating its index.

The divide() function in Ruby's set class provides a convenient way to partition sets into subsets based on specified conditions, offering flexibility in data manipulation and analysis.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved