Tag:

Ruby中的NameError

对于这段代码: class myBaseClass def funcTest() puts “baseClass” end end myBaseClass.new.funcTest 我收到一个错误: NameError: undefined local variable or method `myBaseClass’ for main:Object from c:/Users/Yurt/Documents/ruby/polymorphismTest.rb:9 from (irb):145:in `eval’ from (irb):145 from c:/Ruby192/bin/irb:12:in `’ irb(main):152:0> x=myBaseClass.new 当我尝试x=myBaseClass.new ,我得到: NameError: undefined local variable or method `myBaseClass’ for main:Object from (irb):152 有人已经遇到过这个问题吗? 我不认为我的代码可能是错的。

Rails类<< self

我想了解下一个例子中的class << self代表什么class << self 。 module Utility class Options #:nodoc: class << self def parse(args) end end end end

Ruby:对类定义的显式范围

免责声明:代码取自ruby公案 这是对类中常量范围的讨论。 这是几个类的定义: class Animal LEGS = 4 def legs_in_animal LEGS end end class MyAnimals LEGS = 2 class Bird < Animal def legs_in_bird LEGS end end end 此时做MyAnimals::Bird.new.legs_in_bird结果为2,我理解为什么 – 在inheritanceheirarchy之前搜索常量的词法空间。 然后定义这个类: class MyAnimals::Oyster < Animal def legs_in_oyster LEGS end end 该教程说,现在调用MyAnimals::Oyster.new.legs_in_oyster结果为4,我无法弄明白。 在我看来,Oyster是MyAnimals中的嵌套类,因此我希望它的行为与Birds类在上面的行为相同。 我遗漏了一些关于用明确的范围界定声明类Oyster的关键信息。 任何人都可以向我解释这个吗? 我通过谷歌发现了数百个ruby课程教程,但没有一个能解决这个问题。 先感谢您…

从任意哈希初始化Ruby类,但只有具有匹配访问器的键

有没有一种简单的方法来列出已在Ruby类中设置的访问器/阅读器? class Test attr_reader :one, :two def initialize # Do something end def three end end Test.new => [one,two] 我真正想要做的是允许初始化接受具有任意数量属性的哈希,但只提交已经定义了读者的哈希。 就像是: def initialize(opts) opts.delete_if{|opt,val| not the_list_of_readers.include?(opt)}.each do |opt,val| eval(“@#{opt} = \”#{val}\””) end end 还有其他建议吗?

在Ruby中替换to_s方法。 不打印出所需的字符串

所以,我刚刚开始学习Ruby,我在我的类中包含了一个to_s方法,这样我就可以简单地将Object传递给puts方法,让它返回的不仅仅是Object ID。 我犯了一个错误,并将其定义为: def to_s puts “I’m #{@name} with a health of #{@health}.” end 代替: def to_s “I’m #{@name} with a health of #{@health}.” end 所以,当我在使用第一个代码块时执行此操作: player1 = Player.new(“larry”) puts player1 当我执行上面两行代码而不仅仅是字符串时,我得到一个对象ID和一个字符串。 为什么是这样? 我得到这个输出: I’m Larry with a health of 90. # 我试图考虑为什么程序的第一个版本不只是打印出字符串到控制台,而是返回对象ID和字符串。 我认为当我将对象传递给puts时,所发生的一切就是puts转向并调用to_s方法来获取玩家的字符串表示。 对?