Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Convert strings to different types

Tags:

elixir

I have a stringified value that may be an integer or boolean ("20", "true"). I would like to cast the value to it's type, however, when I do a conversion on the wrong type, I get a runtime error:

iex> String.to_existing_atom("20")
** (ArgumentError) argument error
    :erlang.binary_to_existing_atom("20", :utf8)

iex> String.to_integer("true")    
** (ArgumentError) argument error
    :erlang.binary_to_integer("true")
like image 467
jordan Avatar asked Apr 26 '26 19:04

jordan


1 Answers

If you need to convert only integers and booleans from strings you may do something like this:

defmodule Converter do
  def convert!("true"), do: true
  def convert!("false"), do: false
  def convert!(num), do: String.to_integer(num)
end

Sample usage:

iex(4)> Enum.map(["20", "true", "-5", "false"], &Converter.convert!/1)
[20, true, -5, false]

If you are dealing with json you may want to consider using a parsing library such as Poison.

like image 96
bla Avatar answered Apr 29 '26 21:04

bla