From: Daniel Ferguson Date: 2013-03-25T05:06:58+09:00 Subject: Re: Writing a game, trying to make dynamic loops Hi! Would you be happy accessing players by an array index? eg. players[0].name would return player 1's name players[2].score would return player 3's score etc. Possibly not the best solution but I think it would work: class Player def initialize(name) @name = name end end puts "How many players?" players = Array.new(gets.to_i) #.to_i converts the string to an integer if possible # players is now an array the size of entered number and will look like this if player entered '3' [nil, nil, nil] # map! lets you alter array elements and goes through them exactly as .each does # have a look at the documentation for more info n = 1 players.map! { |e| puts "Name of player #{n}?" e = Player.new(gets.chomp()) #chomp strips off the newline character } players[0] will give you access to your first player object players[1] etc. you could use players[1].name or players[2].score to use your player methods once you've defined them # inspecting the array gives you a list of Player objects # you could instead use hashes to access your objects with some tweaks to the assignment process # also are you sure you want objects named after what is set as the player name? On 24 Mar 2013, at 16:55, "Nick G." wrote: > Hey there, > > This is likely very simple, but I haven't stumbled across the right code > yet. > > I want the following to take place: > [code] > class Player > end > puts "How many players?" > players = gets() > players.each { # Trying to make this loop run based on the number > entered, but writing it this way causes an error > puts "Name of player?" > playername = gets() > # This is also where I get stuck. I want to make an object > named after what is stored as playername > playername = Player.new??? Doesn't seem to work > } > [/code] > > I did go through several Google searches, and I can't seem to find the > location of a break down on loops that run based on user input. Any > tips would be appreciated! :) > > Thanks, > Draekhost > > PS: I hope this code was small enough to just toss in here. Sorry if > it's not! > > -- > Posted via http://www.ruby-forum.com/. >