2012-08-03 50 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