0

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

Abraham P
  • 15,029
  • 13
  • 58
  • 126

1 Answers1

2

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
Andrew Haines
  • 6,574
  • 21
  • 34
  • 1
    I'd never though to use splat that way! (I've only really used it in method definition as in "unknown number of params in Array"). This is awesome, and I love Ruby even more then I previously did – Abraham P Jan 15 '13 at 19:13
  • Thanks a lot for splat operator suggestion! I've applied it but still have issues: – Andrey Brindeyev Jan 15 '13 at 19:20
  • I've changed my line to `*pool_map.keys.map{|val| "DS:#{val}:GAUGE:#{ti * 2}:0:U" },` but still getting a lot of errors like `syntax error, unexpected tSTRING_BEG, expecting tAMPER` – Andrey Brindeyev Jan 15 '13 at 19:21