我试图在Ruby中调用RRD.create
。我的RRD变量存储在一个散列中,我需要构造一个RRD.create
调用。下面是我的代码:
pool_map = {
"cleanup" => "Cleaning up",
"leased" => "Leased",
"ready" => "Ready"
}
start = Time.now.to_i
ti = 60 # time interval, in seconds
RRD.create(
rrdfile,
"--start", "#{start - 1}",
"--step", ti, # seconds
pool_map.keys.map{|val| "DS:#{val}:GAUGE:#{ti * 2}:0:U" }.collect,
"RRA:LAST:0.5:1:#{86400 / ti}", # detailed values for last 24 hours
"RRA:AVERAGE:0.5:#{5*60 / ti}:#{7*24*60}", # 5 min averages for 7 days
"RRA:MAX:0.5:#{5*60 / ti}:#{7*24*60}", # 5 min maximums for 7 days
"RRA:AVERAGE:0.5:#{60*60 / ti}:#{183*24}", # 1 hour averages for a half of the year
"RRA:MAX:0.5:#{60*60 / ti}:#{183*24}" # 1 hour maximums for a half of the year
)
然而,我从Ruby得到以下错误:
in `create': invalid argument - Array, expected T_STRING or T_FIXNUM on index 5 (TypeError)
我需要指定几个字符串给RRD.create
而不是传递数组。我如何在Ruby中做到这一点?
注:http://oss.oetiker.ch/rrdtool/prog/rrdruby.en.html
您需要"splat"操作符(一元星号):
*pool_map.keys.map{|val| ...}
注意,您不需要最后的collect
,它什么也不做!collect
只是map
的别名,你没有对它做任何事情,因为你没有给它传递一个块。
Splat对于解构数组非常有用:
arr = [1, 2, 3]
a, b, c = *arr
# a = 1; b = 2; c = 3
你可以经常用它来给方法提供参数,就像你想做的
def sum_three_numbers(x, y, z)
x + y + z
end
arr = [1, 2, 3]
sum_three_numbers(*arr)
# => 6
arr = [1, 2]
sum_three_numbers(100, *arr)
# => 103