Discussion on:

Message 44 of 51
0 Votes
+ -
not necessarily, re: OO
Ruby's OO syntax for regular expressions is actually quite easy to use. It's very clean and easy to read -- I just have to think about it differently than I think about Perl regexen.

OO syntax can be made very nice to use with regexen, as Ruby has proven. The problem isn't with an OO approach, but with a noun-centric, obtuse OO approach. Ruby's standard OO syntax for regex handling is a bit more verb-centric (where "method" == "verb") and involves implicit instantiation of a regex object in a method call, where the object to which the message is being passed is the string on which the method operates. For instance:

string_var = 'Java is my language. Java Rules!'
puts string_var.gsub(/Java/, 'Ruby')


. . . with output:
Ruby is my language. Ruby Rules!

You can also do this by passing a block to the String#gsub method:

string_var = 'ruby is my language. ruby rules!'
puts string_var.gsub(/r/) { |char| char.upcase }


. . . with output:
Ruby is my language. Ruby Rules!

Putting it all together (same output):

string_var = 'Java is my language. Java rules!'
puts string_var.gsub(/Java/, 'Ruby').gsub(/r/) { |char| char.upcase }


Compare with Perl's syntax:

my $string_var = 'Java is my language. Java rules!'
$string_var =~ s/Java/Perl/;
$string_var =~ s/r/R/;
print "$string_var\n";


Personally, I think they're different -- but about equally readable and easy to use. Of course, I can understand where the impression that OO syntax for regexen is obtuse and annoying -- because with most OO syntaxes, it is obtuse and annoying. Python comes to mind (largely because regex functionality exists outside the core language), and Java is even worse.
Posted by apotheon
Updated - 1st Oct 2007