Ruby 求解:comparison of String with 0 failed (ArgumentError)

plasmiq · November 24, 2012 · Last by plasmiq replied at November 24, 2012 · 4237 hits

def f(x) if x >0 return x else return -x end end

print "x=" x=gets() puts f(x)

运行,提示"x=" 输入任何值返回都是第二行错误:comparison of String with 0 failed (ArgumentError)

求解

gets() 拿到的是字符串,字符串不能和数字比较大小。

谢~~应该用什么呢?

x = gets().to_i

You need to Sign in before reply, if you don't have an account, please Sign up first.