Emjey
Emjey

Reputation: 2063

How do I total the random numbers generated in ruby

I have the code, that will generate random numbers, unless the generated random number is 0. When the result is 0, the loop breaks.

So when the loop breaks, I want a code, that keeps adding the random numbers that kept generated and display it at the last. Can I do that in 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

This is throwing Dynamic Constant assignment error at Score = Score + myruns which I basically think, its wrong, since the myruns keep changing at every generated event?

So, I would want to create a new variable, that would store the total of all the random numbers generated until the generated random number is 0.

Could anyone help?

Upvotes: 0

Views: 134

Answers (2)

Manuk Karapetyan
Manuk Karapetyan

Reputation: 534

May be you are looking for something like this ?

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

Upvotes: 1

Sagar Pandya
Sagar Pandya

Reputation: 9508

You can do something like this:

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

Using loop this continually creates random numbers from 0 - 6 with rand 7. We use a ternary operator to stop the loop with StopIteration if x == 0, otherwise we push x into the obj array (which is initially []). Finally we sum the obj array.

Key methods: loop, Enumerable#with_object, rand, Array#sum

Upvotes: 0

Related Questions