Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 这是一个讨厌的全球散列吗?_Ruby_Global Variables - Fatal编程技术网

Ruby 这是一个讨厌的全球散列吗?

Ruby 这是一个讨厌的全球散列吗?,ruby,global-variables,Ruby,Global Variables,我听说某些做法,例如全局变量,经常受到反对。我想了解一下,是否一般也不赞成在下面所示的级别上放置散列。如果是这样的话,应该怎样做才能让人们对它微笑呢 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

我听说某些做法,例如全局变量,经常受到反对。我想了解一下,是否一般也不赞成在下面所示的级别上放置散列。如果是这样的话,应该怎样做才能让人们对它微笑呢

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

如果你是出于好奇而问,那么,你所做的似乎是糟糕的设计-在任何语言中都会注意到,
new\u word
调用
finalize
,后者反过来调用
new\u word
-你可能想使用一个循环。看起来你根本不应该使用类变量。使用类变量,您将在所有词典之间共享单词和定义。拥有字典实例的意义在于,该实例中的定义与另一实例中的定义不同。查看下面ThomasSevestre使用实例变量的答案。我在代码中找不到任何全局变量。局部变量
new\u word
(在
new\u word
的方法体中)始终是字符串。我不明白你为什么要在
中返回新单词.to\u str