Search code examples
rubyirb

What is the difference between these two ruby functions?


Function GetTitle when called from ruby shell throws an error "uninitialized constant GetTitle"

While full_title is working fine.

What is the problem with the 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

Solution

  • In Ruby, as per convention, constants begin with an uppercase letter. So when you call GetTitle its being treated as a constant and you get appropriate error (since there is no such constant). However if you call it with a parameter, it will work. This is because of the presence of parameter Ruby is interpreting it as a method. Here:

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

    You can make Ruby believe its a method by using empty parenthesis too:

    GetTitle()
    #=> "Base Title"
    

    This answer explains it beautifully.