是的,這當然是可以的。這是從99 Bottles of Beer project採取:
#
# Rubeer.rb
# by Eric Budd, Jan. 2008
#
# Demonstrates adding functionality to a built-in class, optional method parameters, inline
# conditionals, string replacement, alcohol aversion, and excessively fancy use of hashes.
#
# This borrows the hash from Daniel Straight's excellent implementation for the "wordalize" method
#
class Integer
NUMBER_WORDS = { 0 => "no", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five",
6 => "six", 7 => "seven", 8 => "eight", 9 => "nine",
10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen",
14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen",
18 => "eighteen", 19 => "nineteen",
20 => "twenty", 30 => "thirty", 40 => "forty", 50 => "fifty", 60 => "sixty",
70 => "seventy", 80 => "eighty", 90 => "ninety"}
def wordalize
raise "Invalid number to wordalize - should be in the range (0..99)" unless (0..99) === self
return NUMBER_WORDS[self] if self < 20
wordalized = NUMBER_WORDS[self - (self % 10)]
wordalized += '-' + NUMBER_WORDS[self % 10] unless (self % 10) == 0
return wordalized
end
def bottles
raise "Invalid number of bottles - should be in the range (0..99)" unless (0..99) === self
how_many_bottles = self.wordalize + ' bottle'
how_many_bottles += 's' unless self == 1
return how_many_bottles
end
alias :bottle :bottles # for grammar Nazis
end
def sing(number, teetotaller = false)
beverage = teetotaller ? 'coke' : 'beer'
puts "#{number.bottles.capitalize} of #{beverage} on the wall, #{number.bottles} of #{beverage}."
if number != 0
puts "Take one down, pass it around, #{(number - 1).bottles} of #{beverage} on the wall.\n\n"
else
puts "Go to the store and buy some more, 99 bottles of #{beverage} on the wall."
end
end
99.downto(0) { |number| sing(number) }
# Uncomment the following for the alternative teetotaller version
# 99.downto(0) { |number| sing(number, true) }
有載有多個Ruby版本,但是默認的是對於初學者過於複雜。然而,這一個非常好,你應該能夠理解正在發生的事情。
應該回答你的問題的一點是99.downto(0) { |number| ... }
。這是一個循環,將重複大括號內的任何內容(在這種情況下,sing(number)
)百倍,number
從99
到0
。
另請注意,將數字作爲字符串((99).to_s
)進行轉換並且在需要時將其轉換爲整數效率很低(並且難以辨認);因此,相反,它總是一個整數,並且在你需要它作爲一個字符串之前將它轉換爲字符串,當你顯示時(或者讓字符串連接/插值自動完成,就像這段代碼一樣)。
雖然紅寶石確實有兩個for
和while
循環,他們很少使用(while
)或從不(for
)。相反,Rubyists通常依賴迭代器和枚舉器。其他功能,如Integer#downto
是Integer#upto
,Integer#times
和幾乎所有的最真棒Enumerable
mixin。
你是說像使用printf? [printf](http://ruby-doc.org/core-2.2.3/Kernel.html#method-i-printf) 您可以使用這些字段類型字符來格式化printf:[sprint](http:// ruby-doc.org/core-1.9.3/Kernel.html#method-i-sprintf) – 2015-10-04 03:35:50