ruby-kickstartコースのクラスを作成するときに、私が最初に(そしてむしろばかげて)試みています。私newbish心の中でこの壁に何瓶のビールがありますか?
が、これは動作するはずです - 代わりに私が手:
Class BeerSong
attr_accessor :beers
def initialize(beers)
beers = 0 if beers < 0
beers = 99 if beers > 99
self.beers = beers
end
def print_song
bottlecount = :beers
letters_to_numbers = Hash.new
letters_to_numbers = {
"Ninety" => 90,
"Eighty" => 80,
"Seventy" => 70,
"Sixty" => 60,
"Fifty" => 50,
"Fourty" => 40,
"Thirty" => 30,
"Twenty" => 20,
"Nineteen" => 19,
"Eightteen" => 18,
"Seventeen" => 17,
"Sixteen" => 16,
"Fifteen" => 15,
"Fourteen" => 14,
"Thirteen" => 13,
"Twelve" => 12,
"Eleven" => 11,
"Ten" => 10,
"nine" => 9,
"eight" => 8,
"seven" => 7,
"six" => 6,
"five" => 5,
"four" => 4,
"three" => 3,
"two" => 2,
"one" => 1
}
while bottlecount > 1
bottlecount_primerA = bottlecount.to_s
bottlecount_primerB = bottlecount_primerA[0].to_i*10
bottlecount_primerC = bottlecount_primerA[1].to_i
if bottlecount > 19 && bottlecount_primerC != 0
bottlecount_tens = letters_to_numbers.key(bottlecount_primerB)
bottlecount_singels = letters_to_numbers.key(bottlecount_primerC)
bottlecount_text = "#{bottlecount_tens}-#{bottlecount_singels}"
elsif bottlecount > 19 && bottlecount_primerC == 0
bottlecount_tens = letters_to_numbers.key(bottlecount_primerB)
bottlecount_text = "#{bottlecount_tens}"
elsif bottlecount > 9 && bottlecount < 20
bottlecount_text = letters_to_numbers.key(bottlecount)
end
puts "#{bottlecount_text} bottles of beer on the wall,"
puts "#{bottlecount_text} bottles of beer,"
puts "Take one down, pass it around,"
bottlecount -= 1
end
puts "one bottle of beer on the wall,"
puts "one bottle of beer,"
puts "Take one down, pass it around,"
puts "zero bottles of beer on the wall"
end
Bottleman = BeerSong.new (99)
Bottleman.print_song
はしばらくの間、私の頭を悩まれて28が "DEF print_songを" ですが、わからない:
rubytest.rb:28:in `<main>': uninitialized constant BeerSong (NameError)
RBなぜクラスは行きたくないのですか?
ルビーでは、 'class'は小文字です。また、変数 'Bottleman'を小文字にしたいと思っています。タブの代わりにインデント用に2つのスペースを使用するのは、Rubyのコミュニティ標準です。空のハッシュを作成したハッシュに置き換えるだけで 'Hash.new'を使う必要はありません(' letters_to_numbers = {...} 'はあなたのために別のハッシュを作成します)。 –