From: Robert Klemme Date: 2013-03-26T07:04:06+09:00 Subject: Re: Choice of methods/implementation (was: Writing a game, trying to make dynamic loops) On Mon, Mar 25, 2013 at 7:55 PM, tamouse mailing lists wrote: > Since otherwise I'd be hijacking, I'm starting a new thread on this: > > On Mon, Mar 25, 2013 at 6:52 AM, Robert Klemme > wrote: >> On Mon, Mar 25, 2013 at 9:40 AM, Hans Mackowiak wrote: >>> how about this? >>> >>> puts "How many players?" >>> players = Array.new(gets.to_i) do |n| >>> puts "Name of player #{n+1}?" >>> Player.new(gets.chomp) >>> end >> >> I'd rather use #times with #map: >> >> players = Integer(gets).times.map do |i| >> puts "Name of player #{n+1}?" >> Player.new(gets.chomp) >> end I just notice, there is a typo in the name prompt. Should have been puts "Name of player #{i+1}?" > Could you say why, Robert? Obviously there's more than one way to do > something, but I am interested in why you'd choose this way? Oh, it's probably rather a matter of taste. When the "automatic" to_enum was introduced for block methods which were called without a block I took on the habit of using that feature since I find it elegant. There's absolutely nothing wrong with your solution. In fact, it might be a more efficient. I'd just point out that using Integer() is more robust than String#to_i because it will ensure the argument *is* actually a String representing an integer. > I don't very much like the previous Array.new() {} either, although > being 1-based might be easier for some to understand, but breaks my > oh-so-long-established zero-based array mentality. I'd have approached > this with #reduce. I'd appreciate hearing your thoughts on the > trade-offs. Which previous Array.new {} do you mean? The one with the separate counter variable? I don't think this calls for #inject / #reduce. IMHO #map is a better choice here since you do not need to explicitly deal with the Array copied into. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/