【问题标题】:ruby def function code not working [closed]ruby def功能代码不起作用[关闭]
【发布时间】:2016-03-23 04:51:08
【问题描述】:

更正这段代码,让 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

【问题讨论】:

  • 期望值是多少?您的 greet 参数名称应该 not@ 符号,并且您不需要它们,因为您正在插入实例变量。此外,当您的代码有错误时,您应该发布它。
  • 我同意,您应该在提问时添加更多细节。它的措辞使它看起来像是一项家庭作业。
  • 欢迎来到 Stack Overflow。 “更正此代码”?让我们考虑一下 Stack Overflow 是什么:在您向我们提供适当的所需信息后,我们会帮助您调试代码问题。阅读“How to Ask”和“minimal reproducible example”,看看你是否做到了。

标签: ruby methods syntax-error


【解决方案1】:

你可以改写成:

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"

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2015-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 2018-05-13
        相关资源
        最近更新 更多