Can someone explain why eval is returning the string, rather than the result of the expression?
perms=["12+2","22","-2+"]
perms.each { |line|
matches=/^[\d]+[+-\/\*]{1}[\d]+$/.match(line)
s=matches.to_a
puts s
puts eval(s.to_s)
}
s = matches.to_a is an array ["12+2"], the eval(s.to_s) will return the array ["12+2"], and when you print it, you will get the output 12+2, a string representation of the array ["12+2"].
You should be evaling the element of the array, in this case, s[0] or s.first.
Fix it like this:
perms=["12+2","22","-2+"]
perms.each do |line|
matches=/^[\d]+[+-\/\*]{1}[\d]+$/.match(line)
if matches
s = matches.to_a
puts eval(s.first)
end
end
matches can be nil if there was no match. Use eval only if its not nil by checking if matches
You could further simplify the code and write something like this:
perms=["12+2","22","-2+"]
perms.each do |line|
puts eval(line) if line =~ /^[\d]+[+-\/\*]{1}[\d]+$/
end
String#scan instead of match to avoid check for nil. The former always returns an array, possibly empty.
[\d]is the same as\dand[+-\/\*]{1}is the same as[+-\/*], so your expression can be simplified to/^\d+[+-\/*]\d+/.eval. Instead, you could use/^(\d+)\+(\d+)$/and calculate the result via$1.to_i + $2.to_i. Same for subtraction, multiplication and division.