'rand':没有将范围隐式转换为整数

时间:2015-05-26 18:27:47

标签: ruby

这是代码:

#this is the array that the numbers are stored on and where x is created
@numbers =    [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90]

#getting the lowest number and taking away 1 so it matches the number at the appropiate index in the array
def get_low()
    number1 = $stdin.gets.chomp
    new1 = number1.to_i - 1
end

#getting the highest number and taking away 1 so it matches the number at the appropiate index in the array
def get_high()
    number2 = $stdin.gets.chomp
    new2 = number2.to_i - 1
end


#these lines ask the user for the highest and lowest possible number, and call the functions needed to create the 10 random numbers
print "\nNote: limit is between 1 and 90"
print "\nLowest possible number is.... "
puts get_low()
print "\nHighest possible number is.... "
puts get_high()
print "\nYour 10 random numbers are now being generated..."
print  "\nYour numbers are: "
print "\n"

#using the rand() function to get 10 random numbers between get_low and get_high
def get_numbers()
    x = "\"#{@numbers[rand("#{get_low}".."#{get_high}")]}\" , \n \"#{@numbers[rand("#{get_low}".."#{get_high}")]}\" , \n\"#{@numbers[rand("#{get_low}".."#{get_high}")]}\" , \n\"#{@numbers[rand("#{get_low}".."#{get_high}")]}\" , \n \"#{@numbers[rand("#{get_low}".."#{get_high}")]}\" , \n\"#{@numbers[rand("#{get_low}".."#{get_high}")]}\" , \n\"#{@numbers[rand("#{get_low}".."#{get_high}")]}\" , \n\"#{@numbers[rand("#{get_low}".."#{get_high}")]}\" , \n\"#{@numbers[rand("#{get_low}".."#{get_high}")]}\" , \n\"#{@numbers[rand("#{get_low}".."#{get_high}")]}\" "
end


puts get_numbers()

但是当我运行它时,我得到关于第29行的以下错误:

in 'rand': no implicit conversion of range into integer (TypeError)
from C:/ruby/ca.rb:29:in 'get_numbers'
from C:/ruby/ca.rb:33:in '<main>'

3 个答案:

答案 0 :(得分:1)

坦率地说,您编写的代码可以通过多种方式进行改进。我希望分享另一种方式来看问题,看一看,看看你是否能够理解它:

[2]

注意:

  • 我避免限制随机数的限制,因为我认为你可能已经这样做了,因为你创建数组的方式。

答案 1 :(得分:0)

(目前我无法访问ruby翻译)

它失败可能是因为你将字符串范围传递给rand方法,但是你应该传递整数范围。删除&#34;来自范围,它应该工作

答案 2 :(得分:0)

看起来你想要一个输入低电平和输入高电平之间的随机数。我会尝试get_low plus rand(get_high)。

报告的问题是这个rand函数想要一个int,你当前正在传递一个范围(a ... b)。