Reputation: 1350
I have a question about a refactoring I have done on an example.
Here is the original code:
class Parts
attr_reader :parts
def initialize(parts)
@parts = parts
end
def size
parts.size
end
def spares
parts.select{|part| part.needs_spare}
end
end
Here is the refactored code:
require 'forwardable'
class Parts
extend Forwardable
def_delegators :@parts, :size, :each
include Enumerable
def initialize(parts)
@parts = parts
end
def spares
select{|part| part.needs_spare}
end
end
In the spares method the original code executed "parts.select{|part| part.needs_spare}" and then in the refactoring it was adjusted to "select{|part| part.needs_spare}". How does the new spares method know what instance variable it is selecting from?
Upvotes: 1
Views: 601
Reputation: 198314
select
is self.select
.self.select
, as all methods in Enumerable
, uses self.each
.self.each
is forwarded to @parts.each
Upvotes: 5