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输出始终为false。为什么?
发布于 2021-02-07 03:54:04
您使用的是Enum.take_random,它返回一个列表。当然,它永远不会与字符串匹配。
对您的代码进行了一些改进:
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.rndhttps://stackoverflow.com/questions/66080510
复制相似问题