我如何在Ruby中自信地递增字符串数字? 我知道我可以调用
"1".next
来得到"2"
, 但这对负数不起作用。"-3".next
=> "-4"
我该如何调用以增加正数和负数的字符串数字?我想要将其作为字符串返回。
"1".next
来得到"2"
, 但这对负数不起作用。"-3".next
=> "-4"
我该如何调用以增加正数和负数的字符串数字?我想要将其作为字符串返回。
#next
然后再将其转换回字符串。'-3'.to_i.next.to_s
("-3".to_i + 1).to_s
,但这不考虑浮点数(如果你需要的话)。你可以使用带有块并匹配正则表达式的gsub
方法来转换和递增。对于负数,next
无法工作,因为它只计算最右边的数字,不关心减号字符。以下代码匹配整数或浮点数,并根据整数类型递增它们:INCREMENTAL = 1
def increment_str(str)
str.gsub(/(-)?\d+(.\d+)?/) { |x| x.include?(".") ? x.to_f + INCREMENTAL : x.to_i + INCREMENTAL }
end
increment_str("-3") => "-2"
increment_str("3") => "4"
increment_str("-3.0") => "-2.0"
increment_str("3.0") => "4.0"
to_i
到to_f
),增加1,并转换回字符串。例如:['-1.23', '-1', '0', '1', '1.23'].each do |str|
int_str_plus_1 = (str.to_i + 1).to_s
float_str_plus_1 = (str.to_f + 1).to_s
puts [str, int_str_plus_1, float_str_plus_1].join("\t")
end
输出:
-1.23 0 -0.22999999999999998
-1 0 0.0
0 1 1.0
1 2 2.0
1.23 2 2.23
x.to_i.next.to_s
- Sergio Tulentsev