On Fri, 6 May 2022 at 14:53, hmdne <hmdne@airmail.cc> wrote:
As per an error you get - there's "no block given" when recursing.
You will need to replace the call `x.list` with `x.list(&block)` to pass
the block.
On 5/6/22 15:48, Peter Hickman wrote:
> I am wanting to use yield on a recursive data structure. Here is a
> simple example
>
> class Fred
> def initialize(xs)
> @data = xs
> end
>
> def list(&block)
> @data.each do |x|
> if x.kind_of? Fred
> x.list
> else
> yield x
> end
> end
> end
> end
>
> f1 = Fred.new([1,2,3,4,5])
>
> f1.list do |x|
> p x
> end
>
> Which as expected displays the number 1 to 5, however when I try this
>
> f2 = Fred.new([100, f1, 200])
>
> f2.list do |x|
> p x
> end
>
> I get 100 and "no block given (yield)" as it tries to recurse. What I
> am expecting to see is 100,1,2,3,4,5,200
>
> Any idea how I can achieve this?