是否可以存储Ruby命令并在以后执行其输出?

时间:2012-08-03 08:53:38

标签: ruby-on-rails ruby

我正在尝试做一些不寻常的事情作为另一个问题的解决方法。我想存储ruby命令并稍后执行它们。

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

以下是一个例子:

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

4 个答案:

答案 0 :(得分:8)

此外,您可以将lambda用于此类任务:

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

更新:

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

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

command_store << lambda { puts my_first_array[0] }

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

答案 1 :(得分:5)

为什么不使用标准函数eval()

e.g。 (来自链接文章)

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

答案 2 :(得分:1)

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

  

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

如果以后位于脚本末尾,您可以使用END

END {
  puts 1
}
puts 2

结果:

2
1    

答案 3 :(得分:0)

就更好的可变范围可见性而言,我建议使用。但是,如果您只想存储和执行, lambda 是一个完美的解决方案。

根据我的理解,我想你想在command_store之外的某个地方访问my_first_array。所以在你的情况下,它将是:

场景I :如果您不想公开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
相关问题