This (ruby) regex thing still gives me a headache , esp when I'm trying to figure out other people's code
"foo@example.com".slice(/@(.*)/, 1)21–24 of 24 posts
This (ruby) regex thing still gives me a headache , esp when I'm trying to figure out other people's code
"foo@example.com".slice(/@(.*)/, 1)One of my favorite patterns: _, username, domain = */([^@]+)@(.+$)/.match("foo@example.com")
Nice. I am intrigued by the leading underscore, are you just using that as a throwaway variable? You could get the username and domain on their own with: username, domain = [*/([^@]+)@(.+$)/.match("foo@example.com")][1..-1] And it is super readable.
username,domain = */([^@]+)@(.+$)/.match("foo@example.com").capturesEarlier quoted context omitted.
> I'm unconvinced it needs special syntax at all. What's interesting is that it's actually not special syntax - at least, it's not special syntax for regex usage. The syntax obj[arg, arg, arg] looks weird because in most languages things that look like subscripts can't have multiple arguments, but it's just sugar for the method call obj.[](arg, arg, arg), which is pretty mundane. The semantics are just the semantics…
Fair enough. I don’t like the special semantics then, that say that string objects take regular expressions as possible slice indices. It's trying to be too cute, and compactness comes at the direct expense of clarity. Basically the reason I don't like Ruby generally, is that everything tries to be too clever by half, too many behaviors crammed into too few parts. It's sort of halfway from Python to Perl.
In a dynamically-typed language there's no reason not to pass a Regexp, or indeed a Fruitbat, to a slice expression, so long as it behaves in some expected way. What I don't like about it is that there's no obvious convention for what that should be. String#[] has two fairly different behaviours depending on whether the argument behaves in one way or another. Because they have the same syntax, they look like they should mean similar things, but whether they're similar is debatable at best; and even if that case is debatable, the semantics of this are completely different:
Proc.new {|x, y| x + y}[2, 3] # => 5
(That is, Proc#[] is aliased to Proc#call, to work around the fact that Ruby's method call syntax is a special case whose semantics are not programmable, and can't be used on Proc objects.)More generally, I think it's a net win that the language detaches syntax from semantics in this way, and allows the semantics to be programmed; but for readability, syntax should still suggest semantics - i.e. a convention that should be followed when defining the semantics. The authors of the Ruby standard library didn't follow such a convention for [].
(foo){2,5}