转换为整数是不是正在执行?

时间:2015-11-25 08:10:14

标签: ruby

我有这段代码:

#require_relative '../lib/hackex/net/typhoeus'
require_relative '../lib/hackex'
require 'rubygems'
require 'faker'

    print "how many farms do you want : "
    choice = gets.chomp
    choice.to_i
    check = choice.is_a?(Integer)
    puts check
    if choice > 250
    puts "Error! you cannot make more than 250 farms at once"
    elsif choice < 250
    puts "Error! you have to make at least one farm..."
    elsif choice.is_a?(Integer) == false
    puts "Error, something went wrong !"
    else
    puts "making #{choice} acounts ! ! !"
    cnt = 1
            while choice>cnt
            gen = Faker::Name.first_name + Faker::Name.last_name
            path=("created1.txt")
            email = gen+'@gmail.com'
            password = Faker::Internet.password(8)
            username = gen.to_s+'/>'
            puts HackEx::Request.Do(http,HackEx::Request.CreateUser(username, email, password, facebook_id = nil))
            cnt +=1
            open(path, 'a') { |f|
                    f << "#{email};"
                    f << "#{password}"
                    f << "\n"
                    }
                puts "Account created!"
                puts "#{choice - cnt} accounts remaining!"
            end
            end

我正在尝试确定选择是否为整数...我选择了.to_i,但它返回false,这意味着它不是整数,它是一个字符串,为什么不切换?
ps:我没有得到任何错误,其余的代码工作正常,除了if部分

2 个答案:

答案 0 :(得分:3)

choice.to_i 返回一个整数,但不会更改choice。如果您希望将choice更改为旧choice的整数值,则需要明确重新分配:

choice = choice.to_i

答案 1 :(得分:1)

引用doc of String::to_i,强调是我的

  

to_i(base = 10)→整数

     

返回将str中的前导字符解释为的结果   整数基数(2到36之间)。

所以你必须将回报分配给某个东西,或者它自己:

choice = choice.to_i