简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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