Appending to an array

Hey everyone. New R. user here. I am trying to create a dice class
that adds the rolled values (a string) into a list. Here’s what I have
so far:

class Die

def initialize(rolls)
@rolled_values = []
@rolls = rolls
end

def roll
@rolls.times do
rolled_value =
“#{rand(1…6)}#{rand(1…6)}#{rand(1…6)}#{rand(1…6)}#{rand(1…6)}”
@rolled_values.push(rolled_value)
end
end

def print_values
puts @rolled_values
end

end

if FILE == $0
test_roll = Die.new(5)
test_roll.roll
test_roll.print_values

end

Here’s an example of what I’m expecting:

[‘13432’, ‘21232’, ‘43612’, ‘44341’, ‘66345’]

Here’s what I’m getting:

13432
21232
43612
44341
66345

What am I doing wrong? Please explain.

This might give you a hint where you’re going wrong:

[1] pry(main)> array = [‘13432’, ‘21232’, ‘43612’, ‘44341’, ‘66345’]
=> [“13432”, “21232”, “43612”, “44341”, “66345”]

[2] pry(main)> puts array
13432
21232
43612
44341
66345

[3] pry(main)> p array
[“13432”, “21232”, “43612”, “44341”, “66345”]

Just as an idea, you could make “roll” more dynamic so you could change
the number of dice and the number of sides each die has:

@rolled_values = []
=> []

def roll( die=6, num=5 )
@rolled_values << num.times.inject(’’){|str,_|str<<rand(1…die).to_s}
end
=> :roll

roll
=> [“62433”]

roll( 8, 5 )
=> [“62433”, “75254”]

p @rolled_values
[“62433”, “75254”]
=> [“62433”, “75254”]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs