2012-08-03 51 views
1

我正在尝试做一些有点不寻常的事情来解决另一个问题。我想存储ruby命令并稍后执行它们。以后可以存储Ruby命令并执行它们的输出吗?

我可以在变量中存储命令,但是我只能将它们打印到屏幕上,我玩弄弄平看看能不能将它们转换为可用形式,但它不起作用。

下面是一个例子:

Command_Store = Array[puts "Hello World", my_first_array = array.new, puts "Hello World again"] 

execute.Command_Store[0] => Hello World 
execute.Command_Store[1] => my.first_array[] 
execute.Command_Store[2] => Hello World again 
+0

这正是Lambda和块用于。 – texasbruce 2012-08-03 09:29:13

回答

8

您也可以使用拉姆达为这样的任务:

command_store = [] 
command_store << lambda { puts "Hello World" } 
command_store << lambda { my_first_array = Array.new } 
command_store << lambda { puts "Hello World again" } 

command_store.each(&:call) 
#=> Hello World 
#=> Hello World again 

UPDATE:

您可以捕获变量my_first_array,这就是所谓的封闭

my_first_array = [3,4,5,6,7] 

command_store << lambda { puts my_first_array[0] } 

command_store.each(&:call) 
#=> ... 
#=> 3 
+0

我可以用这个来输出命令puts my_first_array [0],这样ruby将打印my_first_array [0] – Ninja2k 2012-08-03 10:15:40

+0

@ Ninja2k的内容,请参阅更新 – megas 2012-08-03 13:23:56

+0

对不起,我对这个更复杂的查询有问题,这里是一个例子线索= Array.new 线索<< '电源类型' 线索<< '槽孔' 线索<< '软件包括' \t \t Var100 = clues.rindex( '软件包括') Var101 =“clues [#{Var100}]” command_store = Array.new command_store << lambda {puts“clues [#{Var101}]”} – Ninja2k 2012-08-03 15:18:54

5

为什么不使用标准的功能eval()

例如(从链接的文章)

code = "Time.now" 
result = eval(code) 
puts result 
0

就更好的可变范围知名度,我会推荐使用区块。但是lambda是一个完美的解决方案,如果你只是想存储和执行。

从我的理解,我想你想访问my_first_array在command_store之外的某处。所以你的情况这将是:

情景我:如果你不希望暴露my_first_array,但仍希望以某种方式发挥它。

def command_store 
    puts 'Hello World' 
    # here my_first_array is just a local variable inside command_store 
    my_first_array = Array.new(5) {|i| Random.rand(100)} 
    yield(my_first_array) 
    puts 'Hello World again' 
end 

command_store() do |x| 
    # puts '**Call from outside' 
    puts "The first element is #{x[0]}" 
    # ... 
    puts "The last element is #{x[-1]}" 
    # puts '**Call from outside again' 
end 

# Output: 
# => Hello World 
# => The first element is 41 
# => The last element is 76 
# => Hello World again 

方案II:假设你想赋值语句是有效的外部变量。在这种情况下考虑使用绑定也是一个好主意。

def command_store(var=[]) 
    puts 'Hello World' 
    # here my_first_array is just a local variable inside command_store 
    my_first_array = Array.new(5) {|i| Random.rand(100)} 
    var.replace(my_first_array) 
    puts 'Hello World again' 
    return var 
end 

a = Array.new 
command_store(a) 
puts a[0] 

b = command_store() 
puts b[0] 

# Output: 
# => Hello World 
# => Hello World again 
# => 66 
# => Hello World 
# => Hello World again 
# => 16 
+0

如果你喜欢更多的灵活性,比如能够在没有任何块的情况下调用'command_store()',那么你可以在'yield'后添加'if block_given?'。 – 2012-08-03 11:32:55

1

您已经有一些答案使用lambdas(这是正确的答案)。

我想存储ruby命令并稍后执行它们。

如果是在脚本结束时,您可以使用END

END { 
    puts 1 
} 
puts 2 

结果:

2 
1