Which makes absolute sense because that class indeed does not contain that method, but as I’ve been reading should ruby search the classes parents and grandparents for the method?
That’s correct, but you didn’t declare any superclasses so the superclass will be Object
. Which also doesn’t have an each
method.
If you want an enumerable method, you’ll have to define it yourself – you’ll probably want to iterate over the array.
In that case, you could just define an own each method that just passes the passed block down to the arrays each
method:
class Boyfriends
def each(&block)
@boyfriends.each(&block)
end
end
The &block
here let’s you capture a passed block by name. If you’re new to ruby, this probably doesn’t mean much to you, and explaining how it works is somewhat beyond the scope of this question. The accepted answer in this Question does a pretty good job of explaining how blocks and yield
work.
once you got an each method, you can also pull in Enumerable for a number of convenience methods:
class Boyfriends
include Enumerable
end
Also, to_s
is a method that should return a string, so you should remove the puts
in BoyfriendStats#to_s
.
6
solved Ruby undefined method ‘each’ for class