For example, consider the problem of looping. It may be hard to believe but there are 9 different ways to loop in Ruby.
100.times do
puts "I will not throw paper airplanes in class"
end
1.upto(100) do |i|
puts "#{i}. I will not throw paper airplanes in class"
end
for i in 1..100
puts "#{i}. I will not throw paper airplanes in class"
end
Look at the different solutions for the famous 99 bottles of beer.
i = 99
while i >= 0 do
bottles = "#{i.zero? ? 'No more' : i} bottles"
bottles.chop! if i == 1
puts "Take one down and pass it around, #{bottles} of beer on the wall.\n" unless i == 99
puts "#{bottles} of beer on the wall, #{bottles} of beer."
i -= 1
end
puts "Go to the store and buy some more, 99 bottles of beer on the wall."
i = 99
until i < 0 do
bottles = "#{i.zero? ? 'No more' : i} bottles"
bottles.chop! if i == 1
puts "Take one down and pass it around, #{bottles} of beer on the wall.\n" unless i == 99
puts "#{bottles} of beer on the wall, #{bottles} of beer."
i -= 1
end
puts "Go to the store and buy some more, 99 bottles of beer on the wall."
i = 99
loop do
bottles = "#{i.zero? ? 'No more' : i} bottles"
bottles.chop! if i == 1
puts "Take one down and pass it around, #{bottles} of beer on the wall.\n" unless i == 99
puts "#{bottles} of beer on the wall, #{bottles} of beer."
i -= 1
break if i < 0
end
puts "Go to the store and buy some more, 99 bottles of beer on the wall."
The number of choices gives the programmer the freedom to choose a looping construct based on the expressiveness for a particular problem.
There are several choices for even looping through the elements
of an array.Consider dealing a deck of cards in a game.
suits = ['♥','♠','♦','♣']
cards = 2..10.to_a + ['J','Q','K','A']
deck = suits.collect {|suit| cards.collect {|card| "#{card}#{suit}"}}.flatten.shuffle
deck.each do |card|
deal card
end
for card in deck
deal card
end
deck.each_with_index do |card,i|
deal "Player#{i%4+1}", card
end
No comments:
Post a Comment