我听说全球变量等某些做法常常令人不悦。我想知道是否通常也不赞成将哈希放在下面所示的级别。如果是这样的话,应该如何做才能让它微笑?
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
答案 0 :(得分:3)
您应该检查以下区别:
您接近使用实例变量的工作示例:
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