Hi --
Hi,
Am Montag, 31. Aug 2009, 20:33:19 +0900 schrieb George George:
m=Regexp.new(re,Regexp::IGNORECASE);
if m.match(line)
int1 = m.match(line)[1];
c1 = m.match(line)[2];
int2 = m.match(line)[3];
puts int1<< c1 << int2
end
To the OP: definitely lose the semi-colons
After `m.match(line)' the match is stored in the $~ global
variable. You don't need to execute it three more times.
$~[1] is equivalent to $1.
The `<<' operator modifieds the string `int1'. Better is here the
operator `+'.
It's sure a matter of taste but in general shorter code is easier
to read.
if line =~ /(\d+)(-)(\d+)/i then
int1 = $1
c1 = $2
int2 = $3
puts int1 + c1 + int2
end
This is for the not faint-hearted:
int1, c1, int2 = *$~.captures
It's a little less formidable without the *, which should be OK. A
mixed solution:
int1, c1, int2 = $1, $2, $3
or use Regexp#match and save the match explicitly.
match = m.match(line)
if match
int1, c1, int2 = match.captures
end
or similar.
David
--
David A. Black / Ruby Power and Light, LLC /
http://www.rubypal.com
Ruby/Rails training, mentoring, consulting, code-review
Latest book: The Well-Grounded Rubyist (
http://www.manning.com/black2)
September Ruby training in NJ has been POSTPONED. Details to follow.