Ruby脚本从特定的行或方法开始

时间:2016-12-03 20:18:16

标签: ruby command-line-interface argv

假设我有一个剧本:

!#usr/bin/ruby

# step 1
puts "That's first"
# some code

#step 2
puts "That's second"
# some code

有没有办法将ARGV传递给将从特定行(或步骤,类或其他)开始执行的脚本? 例如,执行$ ruby script.rb -s 2将从第二步开始。

我考虑过使用if\else解析参数,但在这种情况下,脚本会变得更复杂,而且根本不会干。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

使用GOTO时会发生

Bad things

这是一个可以更优雅地解决问题的提案:

在' define_steps.rb'中定义您的步骤:

# define_steps.rb
#####################################################
@steps = []

def step(i, &block)
  @steps[i] = block
end

def launch_steps!(min = 0, max = @steps.size - 1)
  @steps[min..max].each.with_index(min) do |block, i|
    if block
      puts "Launching step #{i}"
      block.call
    end
  end
end
#####################################################

step 1 do
  puts 'Step 1 with lots of code'
end

step 2 do
  puts 'Step 2 with lots of code'
end

step 3 do
  puts 'Step 3 with lots of code'
end

step 4 do
  puts 'Step 4 with lots of code'
end

使用launch_steps.rb单独启动它们:

# launch_steps.rb
require_relative 'define_steps'

launch_steps!
puts "-----------------"
launch_steps!(2,3)

输出:

Launching step 1
Step 1 with lots of code
Launching step 2
Step 2 with lots of code
Launching step 3
Step 3 with lots of code
Launching step 4
Step 4 with lots of code
-----------------
Launching step 2
Step 2 with lots of code
Launching step 3
Step 3 with lots of code
不带参数的

launch_steps!运行每个已定义的步骤,launch_steps!(min,max)minmax之间的每一步运行,launch_steps!(min)运行步骤min继续。

相关问题