I have a class where I want ‘each’ to yield another custom object, so I wrote this:
class Fq_price_set < Array
...
def [](i)
# instead of returning an array, it returns an Fq_price_rec based on the array at i
Fq_price_rec.new(super(i))
end
def each
c = 0
until c == size
yield self.[](c)
c += 1
end
end
...
end
This works: when I do
my_price_set.each {|rec| puts rec.class}
it shows Fq_price_rec. Similarly,
my_price_set.each {|rec| puts rec.mymethod}
outputs the proper value for that method call.
But when I use select, e.g.,
my_price_set.select {|rec| rec.mymethod == 1}
I get an error msg, “undefined method” ‘mymethod’ for Array:… So rec (in ‘select’) is not an Fq_price_rec, it’s an array (of which Fq_price_rec is a subclass). I (obviously mistakenly) thought that overriding ‘each’ would mean that the iterating methods like ‘select’ would use it, i.e., the subclass’s version of ‘each’. Is the simple answer that I must also override ‘select’, or is there a more elegant solution.
Yes, I’m pretty new at Ruby.
TIA
Why not get rid of inheriting from Array, and just have
include Enumerable?