简体   繁体   English

Ruby将字符串推入数组

[英]Ruby pushing strings to an array

I have the following code block and I want to turn the output into an array rather than a series of strings, but I'm not really sure now to push that in. 我有以下代码块,我想将输出转换为数组而不是一系列字符串,但是我现在不确定将其推入。

default['max_log']['instances'] = 20

servers haproxy_backends('max_logger').map { |h|
  ("1".."#{node['max_log']['instances']}").each  { |i|
    "#{h}:83#{i} #{h}:83#{i} check inter 10s rise 2 fall 3"
  }
}

The servers function should be ingesting an array sort of like this where all variables are expanded and resolved. 服务器功能应采用这样的数组类型,其中所有变量均已扩展和解析。

[
  'server1:8301 server1:8301', 
  'server1:8302 server1:8302', 
  'server2:8301 server2:8301', 
  ...
]

I've tried making some really simple version of this in irb for testing, but I really just don't know what I'm doing. 我尝试在irb中制作一些非常简单的版本进行测试,但是我真的不知道自己在做什么。

a = []
# => []

def d
  ('01'..'10').each { |i| puts i }
end
# => :d

a.push(d)
01
02
03
04
05
06
07
08
09
10

# => ["01".."10"]
a

# => ["01".."10"]
d
01
02
03
04
05
06
07
08
09
10
# => "01".."10"

backends = ['maxlog-1', 'maxlog-2']
backends.map { |h| (1..5).each { |i| puts "#{h}:#{i}" } }

ruby test.rb
# => maxlog-1:1
# => maxlog-1:2
# => maxlog-1:3
# => maxlog-1:4
# => maxlog-1:5
# => maxlog-2:1
# => maxlog-2:2
# => maxlog-2:3
# => maxlog-2:4
# => maxlog-2:5

This method will take an array and append elements to it based on a range. 此方法将采用数组,并根据范围将元素追加到数组。 Should give a sufficient example to do what you are trying to do. 应该给出一个足够的例子来做您想做的事情。

myarray = [];

def d(out, min, max)
    (min.to_s..max.to_s).each do |idx|
        out << "my string #{idx}"
    end
end

d(myarray, 1, 10)
puts(myarray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM