0

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
Cœur
  • 37,241
  • 25
  • 195
  • 267
tehAnswer
  • 960
  • 1
  • 13
  • 28

2 Answers2

3
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
user229044
  • 232,980
  • 40
  • 330
  • 338
  • Some great suggestions here, though defining that hash inside the method repeatedly is a bit wasteful. It would be better as a module-level constant. – tadman May 23 '14 at 19:58
  • 1
    teh, re meagar's suggestion of using a hash, consider using symbols rather than strings for the keys (e.g, `:danger` rather than `'danger'`). The reasons are several, as discussed [here](http://stackoverflow.com/questions/8189416/why-use-symbols-as-hash-keys-in-ruby). – Cary Swoveland May 23 '14 at 20:01
0

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

wastl
  • 2,643
  • 14
  • 27