Why does this way of using case not work?

Asked

Viewed 52 times

0

I have the following code:

def label_file_type(type)
    label = 
    case type.to_s
    when ['.jpg', '.jpeg', '.png'].include?(type) then
        content_tag(:span, 'Imagem', class: ['label', 'picture'])
    when ['.mp3'].include?(type) then
        content_tag(:span, 'Áudio', class: 'label audio')
    when ['.txt', '.pdf', '.doc', '.docx', '.odt'].include?(type) then
        content_tag(:span, 'Documento', class: 'label document')
    else
        content_tag(:span, 'Indefinido', class: 'label')
    end
end

This is a helper. For some reason, the only output I get on the screen is Else. It’s as if the instruction is ignoring all comparisons and jumping straight to the last. Can anyone explain to me why it doesn’t work that way?

  • The syntax in Ruby is different, but the reason is explained here: http://answall.com/questions/58192/qual-a-difference-entre-switch-case-e-if-else

1 answer

1

The syntax should be:

def label_file_type(type)
    label = 
    case type.to_s
    when '.jpg', '.jpeg', '.png' 
        content_tag(:span, 'Imagem', class: ['label', 'picture'])
    when '.mp3' 
        content_tag(:span, 'Áudio', class: 'label audio')
    when '.txt', '.pdf', '.doc', '.docx', '.odt' 
        content_tag(:span, 'Documento', class: 'label document')
    else
        content_tag(:span, 'Indefinido', class: 'label')
    end
end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.