Domanda

So I'm learning the methods and in this part I found to ways of writing a method, so I tried to rewrite this:

module ApplicationHelper

  # Returns the full title on a per-page basis.
  def full_title(page_title)
    base_title = "Ruby on Rails Tutorial Sample App"
    if page_title.empty?
     return base_title
    else
      "#{page_title} | #{base_title}"
    end
  end
end

Into this

def full_title(page_title)
    base_title = "Ruby on Rails Tutorial Sample App" 
    return base_title if page_title.empty? 
    return "#{page_title} | #{base_title}" 
end

But in this last case it gives me a lot of errors on /gems/rspec-core-2.13.1/lib/rspec/core/runner.rb, what am I doing wrong?

È stato utile?

Soluzione

Well first off you are looking at the wrong line in your rspec backtrace. It's where the error gets thrown in the rspec code, not what actually is causing it. You should run rspec with the -b option to get actual backtraces from your code.

Also an easier way to write this would be:

# assuming you pass in nil, not "", so #compact would work
def full_title(page_title = nil)
  ["Ruby on Rails Tutorial Sample App", page_title].compact.join(" | ")
end

Alternative way, so it handles blank arguments as well:

def full_title(page_title)
  title = ["Ruby on Rails Tutorial Sample App"]
  title << page_title if page_title.present?
  title.join(" | ") 
end

As for the original issue - i think it's your inconsistent return points.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top