2013-01-15 14 views
0

我試圖在Ruby中調用RRD.create。我的RRD變量存儲在散列表中,我需要構造一個RRD.create調用。這裏是我的代碼:如何在Ruby中調用函數時將數組轉換爲字符串列表?

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 
     ) 

不過,我從紅寶石得到以下錯誤:

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

我需要指定若干字符串RRD.create強似陣列。我如何在Ruby中做到這一點?

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

回答

2

你想要的「圖示」操作符(一元星號):

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

請注意,您不需要collect末出現,它什麼也不做! collect只是map的別名,並且您沒有做任何事情,因爲您沒有通過它。

啪真的是有用的解構陣列:

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 
+1

我從未想過使用啪的一聲! (我只是真的在方法定義中使用它,就像在「數組中未知數的參數」中一樣)。這真棒,我更喜歡Ruby,我之前做過 –

+0

非常感謝splat操作員的建議!我應用了它,但仍然存在問題: –

+0

我已將行更改爲'* pool_map.keys.map {| val | 「DS:#{val}:GAUGE:#{ti * 2}:0:U」},但仍然會出現很多錯誤,例如'語法錯誤,意外的tSTRING_BEG,期待tAMPER' –

相關問題