这个Ruby代码2有什么问题?

时间:2014-06-26 03:01:32

标签: ruby

此代码有什么问题?

class Person
  def initialize(name)
    @name = name
  end
  def greet(other_name)
    "Hi #{other_name}, my name is #{name}"
  end
end

1 个答案:

答案 0 :(得分:2)

将代码编写为

class Person
  def initialize(name)
    @name = name
  end

  def greet(other_name)
   "Hi #{other_name}, my name is #{@name}" # <~~ you missed `@` before name.
  end
end

如果只编写name(而不是@name),Ruby将尝试查找名为name的本地var,但您没有定义任何。然后它将尝试检查您是否定义为name的任何方法,也不存在。所以最后你会得到

undefined local variable or method `name' 

以下是修复后的示例:

#!/usr/bin/env ruby

class Person
  def initialize(name)
    @name = name
  end

  def greet(other_name)
   "Hi #{other_name}, my name is #{@name}" 
  end
end

Person.new("Raju").greet('Welcome!') # => "Hi Welcome!, my name is Raju"