将字符串与 Elixir 列表中的随机值进行比较的问题

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

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

输出总是错误的。 为什么?

您正在使用 Enum.take_random 其中 returns 一个列表。那当然永远不会匹配字符串。

对您的代码的一些改进:

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