Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ruby def函数代码不工作_Ruby_Methods_Syntax Error - Fatal编程技术网

ruby def函数代码不工作

ruby def函数代码不工作,ruby,methods,syntax-error,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 实例变量存储在类的实例中,您不需要将它们作为参数传递: def

更正此代码,使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

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

def greet()

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

end

您可以将其改写为:

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"

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

期望值是多少?您的
greet
param名称不应该有
@
符号,而且您也不需要它们,因为您正在插入实例变量。另外,当你的代码有错误时,你应该发布它。我同意,你应该在提问时添加更多细节。它的措辞让它看起来像一个家庭作业。欢迎来到堆栈溢出。“更正此代码”?让我们考虑一下什么是堆栈溢出:在您向我们提供适当的所需信息后,我们将帮助您调试代码中的问题。阅读“”和“”,看看你是否做到了。