Domanda

I'm trying to call RRD.create in Ruby. My RRD variables are stored in a hash and I need to construct an RRD.create call. Here is my code:

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
        )

However, I'm getting the following error from Ruby:

in `create': invalid argument - Array, expected T_STRING or T_FIXNUM on index 5 (TypeError)

I need to specify a several strings to RRD.create instead of passing array. How can I do this in Ruby?

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

È stato utile?

Soluzione

You want the "splat" operator (unary asterisk):

*pool_map.keys.map{|val| ...}

Note that you don't need the collect at the end there, it does nothing! collect is just an alias for map, and you aren't doing anything with it because you haven't passed it a block.

Splat is really useful for destructuring arrays:

arr = [1, 2, 3]
a, b, c = *arr
# a = 1; b = 2; c = 3

And you can often use it to supply arguments to methods, like you are trying to do

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top