我听说某些做法(如全局变量)经常不受欢迎。我想知道在下面显示的级别上放置哈希是否通常也不受欢迎。如果是这样的话,应该如何做才能让人对它微笑呢?
class Dictionary
@@dictionary_hash = {"Apple"=>"Apples are tasty"}
def new_word
puts "Please type a word and press enter"
new_word = gets.chomp.upcase
puts "Thanks. You typed: #{new_word}"
@@dictionary_hash[new_word] = "#{new_word} means something about something. More on this later."
D.finalize
return new_word.to_str
end
def finalize
puts "To enter more, press Y then press Enter. Otherwise just press Enter."
user_choice = gets.chomp.upcase
if user_choice == "Y"
D.new_word
else
puts @@dictionary_hash
end
end
D = Dictionary.new
D.new_word
end
您应该检查以下两者之间的差异:
- 全局变量、类变量和实例变量
- 类和实例方法
您接近于一个具有实例变量的工作示例:
class Dictionary
def initialize
@dictionary_hash = {"Apple"=>"Apples are tasty"}
end
def new_word
puts "Please type a word and press enter"
new_word = gets.chomp.upcase
puts "Thanks. You typed: #{new_word}"
@dictionary_hash[new_word] = "#{new_word} means something about something. More on this later."
finalize
new_word
end
def finalize
puts "To enter more, press Y then press Enter. Otherwise just press Enter."
user_choice = gets.chomp.upcase
if user_choice == "Y"
new_word
else
puts @dictionary_hash
end
end
end
d = Dictionary.new
d.new_word