34

In Elixir, you can concatenate strings with the <> operator, like in "Hello" <> " " <> "World".

You can also use the pipe operator |> to chain functions together.

I'm trying to write the Elixir code to format the currency for an online game.

def format_price(price) do
  price/10000
  |> Float.round(2)
  |> to_string
  |> <> "g"
end

The above results in a syntax error. Am I overlooking a basic function that can concatenate strings? I know I can define one myself, but that seems like creating unnecessary clutter in my code if I can avoid it.

I realize I can accomplish the same thing, by simply chaining the methods together like to_string(Float.round(price/10000, 2)) <> "g", but this syntax isn't as nice to read, and it makes it more difficult to extend the method in the future, if I want to add steps in between.

Does Elixir have ways to concatenate text using the pipe operator, or is that not possible without defining the method yourself?

Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
Kevin
  • 607
  • 1
  • 5
  • 15

2 Answers2

55

Yes, you can, by passing the full path to the function, which in this case is Kernel.<>:

iex(1)> "foo" |> Kernel.<>("bar")
"foobar"
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • 5
    Thanks - it really threw me off that there's no `String.concat` method in the same way that there's an `Enum.concat` method. I didn't realize that you could call the Kernel methods by just including the full path to the function. – Kevin Jul 25 '16 at 15:49
12

My two cents

I realize I can accomplish the same thing, by simply chaining the methods together like to_string(Float.round(price/10000, 2)) <> "g", but this syntax isn't as nice to read, and it makes it more difficult to extend the method in the future, if I want to add steps in between.

You could use interpolation instead of concatenation. For example, you could do it like this and it's still okay to read, and simple, so easy to modify:

def format_price(price) do
  price = (price / 10000) |> Float.round(2)
  "#{price}g"
end

Answering your question

To answer your question:

Does Elixir have ways to concatenate text using the pipe operator, or is that not possible without defining the method yourself?

As mentioned in the other answer by @Dogbert, you can use Kernel.<>/2

Another solution is to use then/2.

def format_price(price) do
  (price / 10000)
  |> Float.round(2)
  |> to_string()
  |> then(&"#{&1}g")
end

or

def format_price(price) do
  (price / 10000)
  |> Float.round(2)
  |> to_string()
  |> then(&(&1 <> "g"))
end
ryanwinchester
  • 11,737
  • 5
  • 27
  • 45