0
我是新來的Ruby,我正在寫一個腳本,執行以下操作:Ruby optparse - 如何在腳本中使用它?
- 接受命令行參數
- 刪除基於指定參數幾個目錄。
我想什麼它做的事:
./admin_bin -c
Removing files in /opt/sysnovo/tmp and /opt/sysnovo/data
我有這個工作!但是......它不是以紅寶石的方式。
這裏是我的代碼:
#!/usr/bin/env ruby
require 'rubygems'
require 'fileutils'
require 'optparse'
OptionParser.new do |o|
o.on('-c') { |b| $clear = b }
o.on('-h') { puts o; exit }
o.parse!
end
# Two directories we want to specify.
tmp_dir = "/opt/sysnovo/tmp"
data_dir = "/opt/sysnovo/data"
# push this value to a variable so we can evaluate it.
test = $clear
if "#{test}" == "true"
puts "Removing files in #{tmp_dir} and #{data_dir}"
FileUtils.rm_rf("#{tmp_dir}/.", secure: true)
FileUtils.rm_rf("#{data_dir}/.", secure: true)
else
puts "Not removing files."
end
正如你所看到的,我設置$清楚#{}測試評估,並基於這一點。我知道這是不正確的。什麼是正確的方法來做到這一點?稍後我會爲這個腳本添加更多的參數和功能。
P.S.我來自bash背景。
謝謝! 現在,當我開始添加其他功能(我猜這是風格?),我會繼續使用if語句來做到這一點嗎?或者有更多的紅寶石方式來做到這一點?在bash中我可能使用過的函數。這是一個很好的開始使用類的腳本嗎? 不知道我想要做的事,如: '如果$清晰 #無論 end' '如果$ somethingelse #do任何 end' 等 – awojo 2012-07-24 15:20:28
另外一個問題。這段代碼是做什麼的:'{| b | $ clear = b}' – awojo 2012-07-24 15:26:26
你會繼續使用'if'語句。如果你從不重複使用代碼,那麼你現在不需要方法/類。只要做一個線性流動。 '{| B | c = b}將對象傳遞給'b',然後將'c'設置爲'b'。 – 2012-07-24 17:38:34