Ka Mok Ka Mok - 6 months ago 8
Ruby Question

How to split string using regex to split between +,-,*,/ symbols?

I need to tell Ruby in regex to

split
before and after the
+ - * /
symbols in my program.

Examples:

I need to turn
"1+12"
into
[1.0, "+", 12.0]


and
"6/0.25"
into
[6.0, "/", 0.25]


There could be cases like
"3/0.125"
but highly unlikely. If first two I listed above are satisfied it should be good.

On the Ruby docs,
"hi mom".split(%r{\s*}) #=> ["h", "i", "m", "o", "m"]


I looked up a cheat-sheet to try to understand
%r{\s*}
, and I know that the stuff inside
%r{}
such as
\s
are skipped and \s means white space in regex.

Answer

I think this could be useful:

"1.2+3.453".split('+').flat_map{|elem| [elem, "+"]}[0...-1]
# => ["1.2", "+", "3.453"]
"1.2+3.453".split('+').flat_map{|elem| [elem.to_f, "+"]}[0...-1]
# => [1.2, "+", 3.453]

Obviously this work only for +. But you can change the split character.

EDIT:

This version work for every operator

"1.2+3.453".split(%r{(\+|\-|\/|\*)}).map do |x|
    unless x =~ /(\+|\-|\/|\*)/ then x.to_f else x end
end
# => [1.2, "+", 3.453]
Comments