Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case match on integer range

Tags:

elixir

Is there a way to match on a integer range? I am looking to strip characters after a certain number of characters, and add a ellipsis. This is what I want to do, but doesn't match on 1..32.

def cutoff(title) do
    case byte_size(title) do
      _ -> title
      1..32 -> String.slice(title, 1..32) <> " ..."
    end
end
like image 277
rockerBOO Avatar asked Jul 07 '15 15:07

rockerBOO


1 Answers

There are 2 issues here:

  1. When pattern matching in Elixir (and Erlang) the patterns are evaluated top to bottom. In your case, you have a catch all clause (the ignored variable _) above your number range.
  2. You are checking against the value for the range 1..32 - byte_size won't return a range , it will return an integer. If you want to check within a range then you must use a guard.

If you swap the order of your matches and use a guard then it will work:

def cutoff(title) do
    case byte_size(title) do
      x when x in 1..32 -> String.slice(title, 1..32) <> " ..."
      _ -> title
    end
end

You may also want to slice from 0 instead of 1 so the first character doesn't get cut off.

like image 130
Gazler Avatar answered Oct 07 '22 18:10

Gazler