I have a problem with comparing a string to a value from a list

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)}"



and the output is false

Hello and welcome,

Why do You think taking a random element from a list should equal the first of this list?

Maybe You want Enum.take instead?

it is just an example. I want to use random in another project, but i cannot understand why the output is false

Thank you for your answer.
The case could be simplified:

list_of_chioces = ["rock", "paper", "scissors"]
List.first(list_of_chioces) == "rock" # always returns "false"

Seems really strange, I am researching the documentation, but…

Any ideas are appreciated.

Seems to work here. What’s your version of Elixir? what platform?

iex(9)> list_of_choices = ["rock", "paper", "scissors"]
["rock", "paper", "scissors"]
iex(10)> List.first(list_of_choices) == "rock"
iex(11)> List.first(list_of_choices) == "rock"
iex(12)> List.first(list_of_choices) == "rock"
1 Like

That’s really weird. We are:

Erlang/OTP 23 [erts-11.1.1] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [dtrace]

Interactive Elixir (1.11.0) - press Ctrl+C to exit (type h() ENTER for help

on my Mac OSX and here is what we are trying:

defmodule Enn do
  def rnd do
    lst = ['rock', 'paper', 'scissors']
    tkk = Enum.take_random(lst, 1)
    IO.puts "This take: #{tkk}"
    comp = (tkk  == 'rock')
    IO.puts comp

Here is the output with “rock” randomly picked:

iex(19)> Enn.rnd
This take: rock

That’s because Enum.take_random/2 returns a list and not an element. If you change your check to tkk == ['rock'] the check will pass when 'rock' is returned. Also instead of 'rock' you should be using "rock" (and similarly for the rest of the list). This is because in elixir single quotes refers to a charlist which is something you usually only want to use for interoperability with Erlang.


Thank you a lot, makes sense. I will try your recommendations now.

Best regards.

You are 100% right:

iex(28)> Enn.rnd
This take: rock

only knowing that Enum.take_random/2 returns a list.

Great help and valuable lesson: read the documentation before using a method.


Elixir docs are just lovely.
Open iex > start typing a module > tab to see what’s on offer and then h function. I do this a lot and rarely I have to go elsewhere to move forward.

1 Like

Please note that you can use Enum.random/1 instead of Enum.take_random/2 If you need to pick one random element.


Thank you for this advice, valuable indeed. We’ll receive a string, which is the right approach.