2017-02-04 59 views
0

我有代码,它将生成随机数,除非生成的随机数为0.当结果为0时,循环会中断。我如何总计在ruby中生成的随机数

因此,当循环中断时,我想要一个代码,它会继续添加保留生成的随机数并将其显示在最后。我能用红宝石做到吗?

def batting 
    loop do 
    runs = [0,1,2,3,4,5,6] 
    myruns = runs.shuffle.first 
    Newscore = 
    puts "Press W to hit a shot" 
    user_input = gets.chomp 
    while user_input.include? "W" 
     puts myruns 
     until myruns == 0 
      break 
      Score = Score + myruns 
      break 

这是在Score = Score + myruns抛出Dynamic Constant assignment错误,我基本上认为,其错,因为myruns保持在每生成的事件改变?

所以,我希望创建一个新的变量,将存储的总生成的所有随机数,直到产生的随机数为0

谁能帮助?

回答

1

可能是你正在寻找这样的事情?

def batting 
    runs = [0,1,2,3,4,5,6] 
    final_score = 0 
    puts "Press W to hit a shot" 
    user_input = gets.chomp  

    while user_input.include? "W" 
    myruns = runs.sample 

    if myruns != 0 
     final_score += myruns 
    else 
     break 
    end 

    puts "myruns=#{myruns}","final_score=#{final_score}" 
    puts "Press W to hit a shot" 
    user_input = gets.chomp 
    end 
    puts "myruns=#{myruns}","final_score=#{final_score}" 
end 
+0

感谢你,它实际上打印多个随机数,而不是一次一个,为什么'myruns = runs.sample'创建两次?一次在'while'循环中,下一次在'until'中? –

+0

我上面写的代码,每次按'W'时打印一个随机数。我想创建一个变量,将每次产生的随机数相加,直到myruns = 0,发布“break”并将总和加到最终分数,这样每次调用这个“def”时,它不会打扰最终的分数。为了做到这一点,我需要一个变量来存储总和而不是数组。 –

+0

你能否更清楚地知道你需要用文字表达? –

0

你可以做这样的事情:

def batting 
    loop.with_object([]) do |_,obj| 
    x = rand 7 
    x == 0 ? raise(StopIteration) : obj << x 
    end.sum 
end 

batting #=> 33 
batting #=> 0 
batting #=> 18 

使用loop这种不断产生的随机数从0 - 6 rand 7。如果x == 0,我们使用三元运算符来停止StopIteration的循环,否则我们会将x推入obj数组(最初为[])。最后我们总结obj数组。

主要方法:loopEnumerable#with_objectrandArray#sum

+1

呵,'raise(StopIteration)'?为什么不是一个简单的“休息”? –

+0

@ Sagarpandya82'break'和'Stopiteration'之间的区别? –

+0

@SergioTulentsev我很在意。特别是在阅读这里的评论之后http://stackoverflow.com/a/41173887/5101493 –