Playing with the freedom that Ruby offers in its base features, I found rather easy to alias most operator used in the language, but the Regexp#~ unary prefix operator is trickier.
A first naïve approach would be to alias it in the Regexp class itself
class Regexp
alias hit ~@ # remember that @ stands for "prefix version"
# Note that a simple `alias_method :hit, :~@` will give the same result
end
As it was pointed in some answer bellow, this approach is somehow functionnal with the dot notation calling form, like /needle/.hit. However trying to execute hit /needle/ will raise undefined method hit' for main:Object (NoMethodError)`
So an other naïve approach would be to define this very method in Object, something like
class Object
def ~@(pattern)
pattern =~ $_
end
end
However, this won’t work, as the $_ global variable is in fact locally binded and won’t keep the value it has in the calling context, that is $_ is always nil in the previous snippet.
So the question is, is it possible to have the expression hit /needle/ to restitute the same result as ~ /needle/?