开发者

How to multiply "5x3" string in ruby?

开发者 https://www.devze.com 2023-02-22 09:49 出处:网络
How may I multiply this string: \"5x3\" and get t开发者_开发百科he total as integer?My philosophy tends to be \"get it into a data structure, use the great tools we have for working with data structur

How may I multiply this string: "5x3" and get t开发者_开发百科he total as integer?


My philosophy tends to be "get it into a data structure, use the great tools we have for working with data structures, then convert back if necessary".

"5x3".split('x').map(&:to_i).reduce(&:*)


There are two safe ways of doing this: using eval with $SAFE set to 1 or higher (how high depends on your application), or use a dedicated maths parser. I recommend the second method (much harder to go wrong with that), only use the eval method if you need more than basic arithmetic evaluation.

To do this, install the expression_parser gem with gem install expression_parser. Then you can use the the following code to eval a math expression:

require 'expression_parser'
parser = ExpressionParser::Parser.new
p p.parse("5 * 3") 

This will print out 15.0.


Along the lines of trying to sanitize your input (at least a little), here is my suggestion:

def multiply_from_string(string)
  string.split('x').map { |number| number.to_i }.inject(&:*)
end

Still, kind of ridiculous.


Try this:

eval("5x3".gsub("x","*"))

or if you're a normal paranoid:

eval(str.gsub('x','*').gsub(/[^\d+*-\/]/,''))
0

精彩评论

暂无评论...
验证码 换一张
取 消