Topic: Setting multiple local variables inside a condition

I am trying to refactor this helper code into one method

  def nav_type
    if @current_action == 'letter'
      nav_type = 'nav_letter'   
    else
      nav_type = 'nav_other'
    end
  end

  def content_type
    if @current_action == 'letter'
      content_type = 'content_letter'   
    else
      content_type = 'content_other'
    end
  end


I have tried it six different ways from sunday but ruby ends up mashing my strings into one local variable.

Re: Setting multiple local variables inside a condition

Try this:

def display_type(prefix)
  if @current_action == 'letter'
    "#{prefix}_letter"
  else
    "#{prefix}_other"
  end
end

Then you can call it like this:

<%= display_type :content %>
# or
<%= display_type :nav %>

You will probably want to rename it to something more appropriate.

Railscasts - Free Ruby on Rails Screencasts

Re: Setting multiple local variables inside a condition

That will do the trick, but should I assume that it's not possible to set more than one local variable within the scope of a conditional statement?

Re: Setting multiple local variables inside a condition

It's not about setting variables, it's about what the method returns. The local variables you set in the original post did nothing.

It is possible to return multiple objects in a method, but I don't recommend doing this and it's not a solution to your problem. It's more like returning an array with the objects in it.

Railscasts - Free Ruby on Rails Screencasts