Maybe this is redundant, but I have always thought that a Python-ish obj.in?(enum)
would be more intuitive than the Ruby-ish enum.includes?(obj)
:
class Object
def in?(e : Enumerable) : Bool
e.includes?(self)
end
end
1.in? 1..10 #=> true
[1, 2].in? [[1, 2], [3, 4]] #=> true
~See https://github.com/crystal-lang/crystal/wiki/FAQ#why-are-aliases-discouraged.~
EDIT: Sorry, it's not actually an alias.
I don't know about adding something like this to the root object but it would be nice to have in?
@Blacksmoke16 Yeah, it's true that it isn't technically an alias, but I think the principle is the same: it merely provides an alternative to something the language already supports. Probably not a good idea.
I actually don't mind this, I've written if {a, b, c}.includes? x
a bunch of times to avoid a case
with a single when
, and if x.in? {a, b, c}
is nicer.
I'm pretty ambivalent, if others in the core team are open im happy to accept a PR.
@RX14 Sorry, should I go ahead and reopen this? Not sure what the proper etiquette is.
@Marzipanzerfaust usually it ends up better to leave it a few days to make sure everyone's had their say before closing.
@RX14 When used with a fixed set of values, x.in?(a, b, c)
could also work. So this would really be a nice way to write disjunctive comparisons with a single reference than x == a || x == b || x == c
.
I actually don't mind this, I've written
if {a, b, c}.includes? x
a bunch of times to avoid acase
with a singlewhen
, andif x.in? {a, b, c}
is nicer.
Note that you'll need parentheses because the parser will think it's a block
Is the only advantage to write an expression the other way around?
Having two redundant methods will produce different styles: those who prefer includes?
, others prefering in?
, and code with both mixed.'
I thought adding methods to Object
was something to avoid.
There is also Enumerable#any?
, which is quite powerful.
@straight-shoota yeah, a
def in?(*values)
self.in? values
end
would be neat
Aliases on the same object (different names for the same method) are similar but different to shortcuts on other objects.
This is on the borderline of breaking the no-aliases rule, which is why i'm open to the rest of the core team's input instead of rejecting it.
My reasoning for this was similar to the existence of String#match
versus Regex#match
: one is simply the reverse of the other but is slightly more convenient in certain situations, especially in method chains.
In any case, the Enumerable
annotation must not be put in Object
, because it will make it depend on the Enumerable
module (object
is before enumerable
in prelude)
Most helpful comment
I actually don't mind this, I've written
if {a, b, c}.includes? x
a bunch of times to avoid acase
with a singlewhen
, andif x.in? {a, b, c}
is nicer.I'm pretty ambivalent, if others in the core team are open im happy to accept a PR.