Skip to content

Instantly share code, notes, and snippets.

@Willamin
Last active March 3, 2020 22:53
Show Gist options
  • Save Willamin/00c6987f1553d50672e3f962483c64e2 to your computer and use it in GitHub Desktop.
Save Willamin/00c6987f1553d50672e3f962483c64e2 to your computer and use it in GitHub Desktop.
# with this, appropriate as_n_tuple methods are generated as used
class Array(T)
macro method_missing(call)
{% if call.name =~ /as_(\d+)_tuple(\?)/ %}
def as_{{$1}}_tuple{{$2}}
{
{% for j in 0..($1 - 1) %}
self[{{j}}]{{$2}},
{% end %}
}
end
{% end %}
end
end
# OLD VERSION:
class Array(T)
{% for i in 1..10 %}
def as_{{i}}_tuple
{
{% for j in 0..(i - 1) %}
self[{{j}}],
{% end %}
}
end
def as_{{i}}_tuple?
{
{% for j in 0..(i - 1) %}
self[{{j}}]?,
{% end %}
}
end
{% end %}
end
# resulting in
class Array(T)
def as_1_tuple
{ self[0] }
end
def as_2_tuple
{ self[0], self[1] }
end
def as_3_tuple
{ self[0], self[1], self[2] }
end
# ...
def as_1_tuple?
{ self[0]? }
end
def as_2_tuple?
{ self[0]?, self[1]? }
end
def as_3_tuple?
{ self[0]?, self[1]?, self[2]? }
end
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment