In the following code, the issue is that after calling method .find_name on an object type of LogsCollection, the returned object becomes a native array and does not remain type LogsCollection. I believe the correct approach might be to create a constructor/initializer that accepts an array and return a brand new object of the correct type. But I am not sure there is not a better way to accomplish this?
Can a Ruby-pro eyeball this code and suggest (at the code level) the best way to make the returned object from .find_name remain type LogsCollection (not array)?
class Log
attr_accessor :name, :expense_id, :is_excluded, :amount, :paid_to
def initialize(name, expense_id, is_excluded, amount, paid_to)
@name = name
@expense_id = expense_id
@is_excluded = is_excluded
@amount = amount
@paid_to = paid_to
end
end
class LogsCollection < Array
def names
collect do |i|
i.name
end
end
def find_name(name)
@name = name
self.select { |l| l.name == @name }
end
end
logs = LogsCollection.new
logs.push(Log.new('Smith', 1, false, 323.95, nil))
logs.push(Log.new('Jones', 1, false, 1000, nil))
logs = logs.find_name('Smith')
puts logs.count
unless logs.empty?
puts logs.first.name # works since this is a standard function in native array
puts logs.names # TODO: figure out why this fails (we lost custom class methods--LogsCollection def find_name returns _native_ array, not type LogsCollection)
end
Final code post-answer for anyone searching (note the removal of base class < array):
class Log
attr_accessor :name, :expense_id, :is_excluded, :amount, :paid_to
def initialize(name, expense_id, is_excluded, amount, paid_to)
@name = name
@expense_id = expense_id
@is_excluded = is_excluded
@amount = amount
@paid_to = paid_to
end
end
class LogsCollection
attr_reader :logs
def initialize(logs)
@logs = logs
end
def add(log)
@logs.push(log)
end
def names
@logs.collect { |l| l.name }
end
def find_name(name)
LogsCollection.new(@logs.select { |l| l.name == name })
end
end
logs = LogsCollection.new([])
logs.add(Log.new('Smith', 1, false, 323.95, nil))
logs.add(Log.new('Jones', 1, false, 1000, nil))
puts logs.names
puts '--- post .find_name ---'
puts logs.find_name('Smith').names
As you can see in the docs
Enumerable#selectwith a block always returns an array. E.g.What you could do is have some sort of constructor for
LogsCollectionthat wraps up a normal array as aLogsCollectionobject and call that infind_name.As requested here’s an example class (I’m at work and writing this while waiting for something to finish, it’s completely untested):
Use like