Skip to content

Support CharLiteral in RangeLiteral#each - #17170

Draft
straight-shoota wants to merge 3 commits into
crystal-lang:masterfrom
straight-shoota:feat/rangeliteral.map
Draft

Support CharLiteral in RangeLiteral#each#17170
straight-shoota wants to merge 3 commits into
crystal-lang:masterfrom
straight-shoota:feat/rangeliteral.map

Conversation

@straight-shoota

Copy link
Copy Markdown
Member

Currently, RangeLiteral#each and #map and #to_a as well as {% for range %} only work with numeric ranges. This patch adds support for ranges of CharLiteral, which we can iterate just like NumberLiteral.

Iterating CharLiteral is useful for building lookup tables for characters. They are better readable than the equivalent NumberLiteral expression.

For example:

NUMERIC_CHARS = {% begin %}
    {%
      table = (0...256).map { 0 }
      ('0'..'9').each do |c|
        table[c.ord] = 1
      end
    %}
    Slice.literal({{ table.splat }})
  {% end %}

Theoretically, we could do the same for StringLiteral, although I don't see a big use case for that.

The first two commits are a bit of prefactoring. I'll probably extract them to independent PRs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant