我有一个input = "2 + 3"
想要转换为的字符串"2.0 + 3.0"
。我通过以下两种复杂的方法实现了这一目标:
floats = input.scan(/\d+/).map(&:to_f)
operator = input.scan(/[+,\-,*,\/]/)
operator.unshift(floats.first.to_s)
.push(floats.last.to_s).join(' ')
#=> "2.0 + 3.0"
或者:
input.split(/\s+/)
.map{|i| ['+','-','*','/'].include?(i) ? i : i.to_f }
.join(' ')
#=> "2.0 + 3.0"
有没有更简单或更好的方法来做到这一点?
我假设您只在谈论转换整数,而所有其他答案都假设该字符串仅包含整数。我会去:
'1.0 + 2/4.5 - 15'.gsub(/(?<![\.\d])\d+(?![\.\d])/) { |m| "#{m}.0" }
#⇒ "1.0 + 2.0/4.5 - 15.0"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句