Sobes.tech
Middle

How can unrelated objects be passed to a function?

sobes.tech AI

Answer from AI

They can be passed as separate arguments or packed into a data structure, such as an array or a hash.

# Passing as separate arguments
def my_function(obj1, obj2)
  # ...
end

obj_a = Object.new
obj_b = Object.new
my_function(obj_a, obj_b)
# Passing in an array
def my_function(objects)
  objects.each do |obj|
    # ...
  end
end

objects_arr = [Object.new, Object.new]
my_function(objects_arr)
# Passing in a hash
def my_function(objects)
  objects.each do |key, obj|
    # ...
  end
end

objects_hash = { key1: Object.new, key2: Object.new }
my_function(objects_hash)

The choice of method depends on the number and purpose of the objects, as well as the desired code readability. Arrays or hashes are convenient when there are many objects or they have a logical grouping.