Problem with comparing string to random value from a list in Elixir

Viewed 83
defmodule Takes do
  def rnd do
    lst = ["rock", "paper", "scissors"]
    tke = Enum.take_random(lst, 1)
    IO.puts "#{tke}"
    IO.puts "#{List.first(lst)}"
    IO.puts "#{tke == List.first(lst)}"
  end
end

Takes.rnd

The output is always false. Why?

1 Answers

You are using Enum.take_random which returns a list. That of course will never match a string.

Some improvements to your code:

defmodule Takes do
  def rnd do
    lst = ["rock", "paper", "scissors"]
    tke = Enum.random(lst) # this will return a single item, not a list
    IO.inspect(tke) # no need for string interpolation, also if you used inspect before
                    # you would see that `tke` was indeed a list
    IO.puts hd(lst) # hd and tl are both very useful functions, check them out
    tke == hd(lst)  # the last statement in a function is the return value (and when
                    # using `iex` will be printed)
  end
end

Takes.rnd
Related