这两个 ruby 函数有什么区别?

What is the difference between these two ruby functions?

从 ruby shell 调用函数 GetTitle 时抛出错误 "uninitialized constant GetTitle"

虽然 full_title 工作正常。

GetTitle 有什么问题?

def GetTitle(pageTitle = '')
  baseTitle = "Base Title"
  if pageTitle.empty?
    baseTitle
  else
    pageTitle + " | " + baseTitle
  end
end

def full_title(page_title = '')
  base_title = "Ruby on Rails Tutorial Sample App"
  if page_title.empty?
    base_title
  else
    page_title + " | " + base_title
  end
end

在Ruby中,按照惯例,常量以大写字母开头。因此,当您调用 GetTitle 时,它被视为常量并且您会收到适当的错误(因为没有这样的常量)。但是,如果您使用参数调用它,它将起作用。这是因为参数 Ruby 的存在将其解释为一种方法。这里:

GetTitle
# NameError: uninitialized constant GetTitle
GetTitle('abc')
#=> "abc | Base Title"

您也可以通过使用空括号让 Ruby 相信它是一种方法:

GetTitle()
#=> "Base Title"

This answer explains it beautifully.