ruby def功能代码不起作用

时间:2015-12-16 21:25:44

标签: ruby methods syntax-error

更正此代码,以便greet函数返回预期值。

class Person

  def initialize(name, other_name)

    @name = name

    @other_name = other_name

  end



  def greet(@other_name, @name)

    "Hi #{@other_name}, my name is #{@name}"

  end

end

3 个答案:

答案 0 :(得分:3)

您可以将其重写为:

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

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

c = Person.new("Sam", "Ruby")

2.1.0 :073 > c.greet
 => "Hi Ruby, my name is Sam"

答案 1 :(得分:1)

实例变量存储在类'例如,您不需要将它们作为参数传递:

def greet()

    "Hi #{@other_name}, my name is #{@name}"

end

答案 2 :(得分:1)

您需要从greet方法中删除@符号。参数不能是实例变量。