pretty new to ruby and object oriented programming in general. Looking for the Ruby Way of things.
I want to know how to package objects into an array so that I can iterate over them in another class
Currently I am doing it manually with:
bags = []
bag1 = Bag.new("large")
bag2 = Bag.new("medium")
bag3 = Bag.new("small")
bag4 = Bag.new("large")
bags << bag1
bags << bag2
bags << bag3
bags << bag4
But I feel there must be a better way to do this assignment automatically. Should I create a separate Bags class and do it there? Or is this the best approach? Or should I add a bags method in Customer? Not entirely sure how to go about this in the most elegant way?
Here is all my code:
class Customer
def bag_check(bags)
bags.each do |bag|
puts bag.size
end
end
end
class Bag
attr_reader :size
def initialize(size)
@size = size
end
end
bags = []
bag1 = Bag.new("large")
bag2 = Bag.new("medium")
bag3 = Bag.new("small")
bag4 = Bag.new("large")
bags << bag1
bags << bag2
bags << bag3
bags << bag4
customer = Customer.new
customer.bag_check(bags)
What would be your approach? also I would appreciate any insight into how to think about the problem in addition to code, so that I can know how to approach a problem the next time I face something similar. Thanks!