[LRUG] Rewriting Array#each in ruby - a talk idea

Frederick Cheung frederick.cheung at gmail.com
Fri May 24 06:57:19 PDT 2024


Hi everyone,

I come to you bearing a plea for talks with a twist. You may have read
recently that Array#each has being reimplemented in ruby

An earlier version of this [idea][1] should be pretty understandable to the
average rubyist:

```
def each
  unless block_given?
    return to_enum(:each) { self.length }
  end
  i = 0
  while i < self.length
    yield self[i]
    i = i.succ
  end
  self
end
```

There's some handwaving dealing with blocks/chaining enumerators but other
than that it is just yielding elements from the array one at a time

What was actually [merged][2] is quite different:

```
def each
  Primitive.attr! :inline_block
  Primitive.attr! :use_block

  unless defined?(yield)
    return Primitive.cexpr! 'SIZED_ENUMERATOR(self, 0, 0, ary_enum_length)'
  end
  _i = 0
  value = nil
  while Primitive.cexpr!(%q{ ary_fetch_next(self, LOCAL_PTR(_i),
LOCAL_PTR(value)) })
    yield value
  end
  self
end
```

While the structure is still similar - do enumerator things if no block is
given, else yield the array elements in order - the meat is very different
and almost looks like inlining chunks of c into ruby.

I think there is a really interesting talk (or several) arising from this:
what does this actually mean / do? Is this really writing ruby? Why is this
a good thing to do in the first place?

However I've done plenty of speaking at LRUG, most recently just 6 weeks
ago, so rather than submit you all to me droning along I'd like to throw
this idea back to the community for someone else to turn into a talk.
Depending on the scope this could be a 5-10 minutes or 20 minutes+ - it all
depends on how deeply you want to probe.

If wanted, I'm happy to offer any help you might need (this could just be
throwing ideas around for directions in which to take it, talking through
technical details, listening to early versions of the talk - whatever
helps).
I hope this helps someone get over that first hurdle of working out what to
speak about.

Please do get in touch with talks at lrug.org whether you'd like help or not -
there's no sense in duplication of effort

Best,

Fred



[1]:
https://github.com/ruby/ruby/pull/6687/files#diff-a82de4e9dc81d7299580f290adb1aa3c2a6a9c6e02d4d9ff9123c206ec2cd818R44
)
[2]:
https://github.com/ruby/ruby/blob/e49d68bf2732cf467a1532283de4a1716e238677/array.rb#L44
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20240524/6af1b3bf/attachment.htm>


More information about the Chat mailing list