【问题标题】:Elixir generating contentElixir 生成内容
【发布时间】:2016-10-24 01:05:34
【问题描述】:

Elixir 初学者在这里!我正在尝试基于配置文件生成 bash 脚本。当我迭代配置并打印我生成的字符串时,一切都很好。但是,当我尝试连接或附加到列表时,我什么也得不到!

def generate_post_destroy_content(node_config) do
  hosts = create_post_destroy_string(:vmname, node_config)
  ips = create_post_destroy_string(:ip, node_config)
  content = "#!/bin/bash\n\n#{hosts}\n\n#{ips}"
  IO.puts content
end

def create_post_destroy_string(key, node_config) do
  # content = ""
  content = []
  for address <- node_config, do:
    # content = content <> "ssh-keygen -f ~/.ssh/known_hosts -R #{address[key]}"]
    content = content ++ ["ssh-keygen -f ~/.ssh/known_hosts -R # {address[key]}"]
    # IO.puts ["ssh-keygen -f ~/.ssh/known_hosts -R #{address[key]}"]
  content = Enum.join(content, "\n")
  content
end

我的输出

#!/bin/bash




=========END=========

【问题讨论】:

    标签: elixir


    【解决方案1】:

    Elixir 中的变量是不可变的。您的代码在 for 的每次迭代中创建一个全新的 content 。对于这个特定的代码,您利用for 返回do 块的评估值列表的事实:

    def create_post_destroy_string(key, node_config) do
      for address <- node_config do
        "ssh-keygen -f ~/.ssh/known_hosts -R #{address[key]}"
      end |> Enum.join("\n")
    end
    

    如果您需要进行更复杂的计算,例如仅在某些条件下添加列表和/或为某些条件添加多个列表,您可以使用Enum.reduce/2。有关详细信息,请查看this answer

    【讨论】:

      猜你喜欢
      • 2019-08-25
      • 2017-08-12
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多