Hello all,
I am converting a Perl program to Ruby in order to learn Ruby. There is
an expression that takes a string, (“1 3/4” or “5”, for example)
determines what kind of fraction was entered, and assigns variables (w,
n, d), appropriately. If a whole number was entered, then it assigns
the variables differently, of course.
The expression first checks for the presence of a slash ("/") to
determine if it is a fraction or whole number. Then, using the
conditional operator, assigns the variables, appropriately.
Here are the two expressions:
Perl:
my ($w, $n, $d) = ( $frac_str =~ /\// )
? $frac_str =~ /(?:(\S+) )??(\S+)\/(\S+)/
: ( 1, $frac_str, 0 );
Ruby:
w, n, d = frac_str.match(/\//) \
? frac_str.match(/(?:(\S+) )*?(\S+)\/(\S+)/).captures \
: 0, frac_str, 1
puts "w: #{w}, n: #{n}, d: #{d}" # check assignment
I used irb to test the regex and it works just fine:
exp = Regexp.new(/(?:(\S+) )?(\S+)/(\S+)/)
=> /(?:(\S+) )?(\S+)/(\S+)/
str = “1 3/4”
=> “1 3/4”
n, w, d = str.match(exp).captures
=> [“1”, “3”, “4”]
w
=> “3”
n
=> “1”
d
=> “4”
But, the above version outputs:
w: 134, n: 1 3/4, d: 1
It appears to recurse over the regex and duplicate the captures. But,
since I am new to this language, I know I can use an ‘if…else’
statement, but since I am coming from Perl, I figured that a similar
expression would “just work”!
Thanks for your time and input,
Derrick