如何在ruby中为字符串添加添加值?

时间:2017-01-25 11:10:15

标签: ruby string

我有一个文件为machine.yml:

machines:  
 A:
    ip: 10.11.12
    pass: vass
    user: A

 B:
    ip: 10.11.13
    pass: grass
    user: B

 C:
    ip: 10.11.14
    pass: pass
    user: C

在ruby中,文件正在解析如下:

machines = YAML.load_file('machine.yml')
    machines[A].each do |letters,hash|
    ## Iterate through entries in YAML file
    machines.each_value do |machines| 
       var += "[" + hash['user'] + "]\n" + hash['ip'] + "\n"
    end

现在,我希望将值作为输出,如下所示:

[A]
10.11.12
[B]
10.11.13
[C]
10.11.14

但我没有得到输出并且收到错误

"': undefined method `+' for nil:NilClass (NoMethodError)"

所以建议我该做什么,以便在变量中得到以下输出,以便变量可以进一步传递给其他函数:

[A]
10.11.12
[B]
10.11.13
[C]
10.11.14

3 个答案:

答案 0 :(得分:1)

您的代码中存在许多问题。

machines[A].each # Where is the variable A defined?

machines.each_value do |machines|  # The variable passed to the block is also machines?

hash['user'] # Where is the variable hash defined?

试试这个。

machines = YAML.load_file('machine.yml')
var = ''
machines.each_value do |hash| 
  var += ("[" + hash['user'] + "]\n" + hash['ip'] + "\n")
end

答案 1 :(得分:0)

这似乎通过irb:

为我工作
machines['machines'].each {|k,v| p "[" + k + "]" + "\n"  + v["ip"]  }

答案 2 :(得分:0)

此方法使用map迭代子哈希和join以获取多行字符串:

require 'yaml'
machines = YAML.load_file('machines.yml')

var = machines['machines'].map{ |id, hash| format("[%s]\n%s", id, hash['ip']) }.join("\n")

puts var
# =>
# [A]
# 10.11.12
# [B]
# 10.11.13
# [C]
# 10.11.14