tehAnswer
tehAnswer

Reputation: 1018

Assignment inside a case statement

I'm trying to do an assignment inside a when-then statement, but it doesn't work as I expected. As I see it, the problem is because, maybe, the case or when-then have a different scope than function. So, how I can reference my variable message_header to write the correct assignment? Or is other stuff?

  def message_notice(type, notice)
    message_header = ""
    case 'type'
      when 'danger' then message_header = 'Oops, something wrong happened'
      when 'success' then message_header = 'Done'
      when 'warning' then message_header = 'Hey, be careful'
      when 'info' then message_header = 'News, news'
    end
    return "<strong>#{message_header}!</strong> #{notice}"
  end

Upvotes: 0

Views: 419

Answers (2)

user229044
user229044

Reputation: 239312

case 'type'

needs to be

case type

You're providing a constant string 'type' to your case, not the variable type. None of your when 's will ever be matched, because none of them equal the string 'type'.

You could also clean this up quite a bit by removing all identical assignments from each branch. Everything evaluates to a value in Ruby, so you the case statement will return the value from whichever branch is selected.

def message_notice(type, notice)
  message_header = case type
                   when 'danger' then 'Oops, something wrong happened'
                   when 'success' then 'Done'
                   when 'warning' then 'Hey, be careful'
                   when 'info' then 'News, news'
                   end
  "<strong>#{message_header}!</strong> #{notice}"
end

You might even want to take it a step further and simply store the type/message as a simple mapping:

def message_notice(type, notice)
  messages = {
    'danger' => 'Oops, something wrong happened',
    'success' => 'Done',
    'warning' => 'Hey, be careful',
    'info' => 'News, news'
  }

  "<strong>#{messages[type]}!</strong> #{notice}"
end

Upvotes: 3

wastl
wastl

Reputation: 2641

Remove the ' ' surrounding the type in the case statement. You are checking if one of your 'danger','success',... strings is equal to 'type'. And thats never the case

Upvotes: 0

Related Questions