在Class方法中,为什么一个方法似乎接受实例变量而另一个方法不接受?

时间:2010-07-19 02:14:54

标签: ruby

在下面的代码示例中,为什么第二个(sheetplus)方法似乎接受实例变量@name和@occupation罚款,但第一个(工作表)方法返回nil?我觉得我错过了一些致命的东西,但我基本上是世界上最差的Ruby程序员。

class Test
def initialize(name, occupation)
  @name = name
  @occupation = occupation
def sheet
  "This is #@name, who is a/an #@occupation"
def sheetplus
  "This is #@name, who is a/an #@occupation, but why does this method succeed where the previous one fails?"
end
end
end
end

4 个答案:

答案 0 :(得分:1)

你真的想要嵌套所有这些定义吗?也许你的意思是:

class Test
  def initialize(name, occupation)
    @name = name
    @occupation = occupation
  end

  def sheet
    "This is #{@name}, who is a/an #{@occupation}"
  end

  def sheetplus
    "This is #{@name}, who is a/an #{@occupation}, but why does this method succeed where the previous one fails?"
  end
end

答案 1 :(得分:1)

其他人已经解释了你的问题是什么,即把你的ends放在错误的地方,但是如果你有兴趣知道为什么你得到你得到的结果那么这就是原因。

t = Test.new('Joe', 'Farmer')

这将创建Test Class的新实例。初始化程序定义了一个名为sheet的新方法,该方法除了定义名为sheetplus的方法

之外什么都不做

如果您现在致电sheetplus,那么您将收到错误,因为sheetplus方法尚不存在(sheet尚未运行以创建它)

t.sheetplus
NoMethodError: undefined method `sheetplus' for 
  #<Test:0x11a9dec @name="Joe", @occupation="Farmer">
    from (irb):14

如果现在调用sheet,它将定义sheetplus方法并返回定义方法的结果(nil)

t.sheet # nil

如果您现在调用sheetplus,则该方法存在,因此成功

t.sheetplus
=> "This is Joe, who is a/an Farmer, but why does this method succeed 
   where the previous one fails?"

答案 2 :(得分:0)

如果这是直接粘贴的代码,则不会关闭初始化或工作表方法定义。

class Test
  def initialize(name, occupation)
    @name = name
    @occupation = occupation
  end
  def sheet
   "This is #@name, who is a/an #@occupation"
  end
  def sheetplus
    "This is #@name, who is a/an #@occupation, but why does this method succeed where the previous one fails?"
  end
end

谁知道那时会发生什么。

答案 3 :(得分:0)

因为您的关键字位于错误的位置。这将按预期工作:

class Test
  def initialize(name, occupation)
    @name = name
    @occupation = occupation
  end
  def sheet
    "This is #@name, who is a/an #@occupation"
  end
  def sheetplus
    "This is #@name, who is a/an #@occupation, but why does this method succeed where the previous one fails?"
  end
end