0

我正在尝试调用RRD.createRuby。我的 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 中做到这一点?

PS http://oss.oetiker.ch/rrdtool/prog/rrdruby.en.html

4

1 回答 1

2

您想要“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
于 2013-01-15T19:06:40.447 回答