新手问题 判断 gets.chomp 获取的类型

ying39 · 2013年09月07日 · 最后由 blacktulip 回复于 2013年09月08日 · 2599 次阅读

还是一个练习,if next_move.is_a?(Numeric)== true 这个我输入任意数字,他都跳转到了 dead 去,是哪里写错了吗?

def gold_room()
    puts "This room is full of gold. How much do you take?"

    prompt
    next_move = gets.chomp
    if next_move.is_a?(Numeric)== true
        how_much=next_move.to_i()
    else
        dead("Man,learn to type a number.")
    end

    if how_much<50
        puts "Nice,you're not greedy,you win!"
        Process.exit(0)
    else
        dear("You greedy bastard!")
    end
end

if next_move.is_a?(Numeric)== true

不能这样判断输入是否是数字 可以这样

if next_move =~ /^[+-]?\d+$/

#1 楼 @Eagle 非常感谢,是正则表达式啊,我没找到号的入门 ruby 书籍,现在是看笨法学 ruby,好像没讲那么深,很多方法和函数都没提到,是否有合适新手入门然后讲比较系统的书推荐呢?不胜感激。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号