Reputation: 1044
I have a transform rule:
"0549$2"
How do I apply this rule to strings in an Elixir? In ruby i use:
format("0549%2$s", *["88", "77"])
=> "054977"
In Elixir I write:
:io.format("0549%2$s", ["88", "77"])
** (ArgumentError) argument error
(stdlib) :io.format(#PID<0.54.0>, "0549%2$s", ["88", "77"])
Because :io.format from erlang does not understand this format
Upvotes: 0
Views: 2585
Reputation: 121010
You might use :io_lib.format/2
. It produces the charlist, that can be converted to binary afterwards:
"0549~i~s"
|> :io_lib.format(~w[77 88])
|> to_string()
#⇒ "054988"
~i
stays for “ignore the next term”~s
for treating the parameter as a binarySidenote: io.format
outputs the formatted string to the IO device, returning :ok
.
Upvotes: 4
Reputation: 222388
So you want to replace all $
followed by an integer with the corresponding element (indexed from 1) of a list? Here's one way using Regex.replace/3
:
defmodule A do
def format(string, list) do
Regex.replace(~r/\$(\d+)/, string, fn _, index ->
Enum.at(list, String.to_integer(index) - 1)
end)
end
end
IO.inspect A.format("0549$2", ["88", "77"])
IO.inspect A.format("0549$1", ["88", "77"])
Output:
"054977"
"054988"
Upvotes: 3