Ruby on rails 为什么Ruby不在类的类名和文件名不匹配的实例中抛出错误?

Ruby on rails 为什么Ruby不在类的类名和文件名不匹配的实例中抛出错误?,ruby-on-rails,ruby,autoload,Ruby On Rails,Ruby,Autoload,为什么Ruby解释器在这个实例中没有抛出NameError呢 class OrangeTurtle self.table_name = 'turtles' end 文件名:orange_turtles.rb这个答案听起来像是在逃避责任,但它不会抛出错误,因为Ruby根本不关心文件名的名称 e、 g.在文件asdfasdf中。此处没有结尾 #!/usr/bin/env ruby module Something class Test def test puts 't

为什么Ruby解释器在这个实例中没有抛出NameError呢

class OrangeTurtle
   self.table_name = 'turtles'
end

文件名:orange_turtles.rb

这个答案听起来像是在逃避责任,但它不会抛出错误,因为Ruby根本不关心文件名的名称

e、 g.在文件
asdfasdf中。此处没有结尾

#!/usr/bin/env ruby
module Something
  class Test
    def test
      puts 'test'
    end
  end
end
class SomethingElse
  def otherThings
    puts 'haha'
  end
end
然后,为了让事情变得更奇怪,我可以有一个单独的文件来修改(猴子补丁)在该文件中定义的类。 在
更多内容中.rb

#!/usr/bin/env ruby
require_relative 'asdfasdf.no_rb_ending_here'
module Something
  class Test
    def test2
      test()
      puts '2'
    end
  end
end
class SomethingElse
  def moreThings
    otherThings()
    puts 'MOAR'
  end
end

Something::Test.new.test2()
# test
# 2
SomethingElse.new.moreThings()
# haha
# MOAR

Ruby很酷——你不会因为不需要引起错误的东西而出错。

这个答案听起来像是逃避责任,但它不会引发错误,因为Ruby根本不在乎你的文件名叫什么

e、 g.在文件
asdfasdf中。此处没有结尾

#!/usr/bin/env ruby
module Something
  class Test
    def test
      puts 'test'
    end
  end
end
class SomethingElse
  def otherThings
    puts 'haha'
  end
end
然后,为了让事情变得更奇怪,我可以有一个单独的文件来修改(猴子补丁)在该文件中定义的类。 在
更多内容中.rb

#!/usr/bin/env ruby
require_relative 'asdfasdf.no_rb_ending_here'
module Something
  class Test
    def test2
      test()
      puts '2'
    end
  end
end
class SomethingElse
  def moreThings
    otherThings()
    puts 'MOAR'
  end
end

Something::Test.new.test2()
# test
# 2
SomethingElse.new.moreThings()
# haha
# MOAR

Ruby非常酷-对于不需要引起错误的东西,不会出现错误。

名称错误或未初始化常量错误只出现在Rails中。原因是,活动记录(也是一种通用设计模式)正在将数据库中的表与模型(或通常与对象)进行映射。 Active Record只能通过文件和类的命名约定进行连接。
正如在另一个答案中提到的,纯ruby不需要遵守这些约定。但是,一般的规则是,将文件命名为它们所包含的类,以使代码更有条理。

名称错误或未初始化常量错误仅出现在Rails中。原因是,活动记录(也是一种通用设计模式)正在将数据库中的表与模型(或通常与对象)进行映射。 Active Record只能通过文件和类的命名约定进行连接。
正如在另一个答案中提到的,纯ruby不需要遵守这些约定。但是,一般的规则是将文件命名为它们所包含的类,以使代码更有条理。

不熟悉任何强制执行此行为的语言。您的问题不清楚。在这种情况下,Ruby为什么会引发
NameError
?它可能引发
名称错误的唯一原因是
类#表(名称
不存在。不熟悉任何强制执行此行为的语言。您的问题不清楚。在这种情况下,Ruby为什么会引发
NameError
?它可以
引发
名称错误的唯一原因是
类#表(名称
不存在。