Andy Varner
Andy Varner

Reputation: 3

ruby shoots my output on to separate lines unncessarily

I have written a dice rolling program that saves both the number of sides a die has as well as the roll of a die. When I try and output the two pieces together ruby decides to throw the two pieces on to separate lines. Why when writing:

what_has_rolled.zip(how_many_sides) do |die, sides| print "Your d#{sides} rolled a #{die}" end

does my output look like:

Your d6 rolled a
Your d5 rolled a
Your d4 rolled a
Your d rolled a 4
Your d rolled a 1
Your d rolled a 3

as opposed to:

Your d6 rolled a 4
Your d5 rolled a 1
Your d4 rolled a 3

and how can I write it so its printed correctly?

Upvotes: 0

Views: 44

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74615

I suspect that your length of how_many_sides is shorter than the length of what_has_rolled. For example, I can reproduce the output above like this:

how_many_sides = [6,5,4]    
what_has_rolled = [nil,nil,nil,4,1,3]
what_has_rolled.zip(how_many_sides) do |die, sides| puts "Your d#{sides} rolled a #{die}" end

gives me the same output as you got:

Your d6 rolled a 
Your d5 rolled a 
Your d4 rolled a 
Your d rolled a 4
Your d rolled a 1
Your d rolled a 3

This is because when the arguments to Array.zip are shorter than the length of the array calling the method, nils are appended:

> what_has_rolled.zip(how_many_sides)
=> [[nil, 6], [nil, 5], [nil, 4], [4, nil], [1, nil], [3, nil]]

To obtain your desired output, you need to ensure that both what_has_rolled and how_many_sides are of length 3. For example:

what_has_rolled = [4,1,3]
how_many_sides = [6,5,4]
what_has_rolled.zip(how_many_sides) do |die, sides| puts "Your d#{sides} rolled a #{die}" end

gives the desired output.

Upvotes: 1

Related Questions