1

我有一个用 Ironruby 编写的脚本,它使用 C# .dll 来检索哈希。然后,我在其余的 Ruby 代码中使用该哈希。我宁愿不在 Ironruby 解释器上运行我的整个脚本。有没有办法在 IR 解释器上运行一段代码,获取哈希值,然后通过常规的 Ruby 解释器执行其余代码?

谢谢

4

1 回答 1

1

一种可能的解决方案是将脚本分成两部分,由 Iron ruby​​ 执行的第一部分必须将其状态保存在 yaml 文件中,然后再将控制权交给将由 ruby​​ 运行的第二部分

这里有一个小演示:

C:\devkit\home\demo>demo
"running program:demo_ir.rb"
"the first part of the script running by the iron_ruby interpreter"
"my_hash attributes:"
"attr1: first value"
"attr2: second value"
"attr3: 2012"
"hash_store_filename:temp.yaml"
"running program:demo_ruby.rb"
"hash_store_filename:temp.yaml"
"the second part of the script running by ruby 1.8.x interpreter"
"my_hash attributes:"
"attr1: first value"
"attr2: second value"
"attr3: 2012"

这里是 ironruby (demo_ir.rb) 第一部分的来源:

require "yaml"
p "running program:#{$0}"
hash_store_filename = ARGV[0]

my_hash = { attr1: 'first value', attr2: 'second value', attr3: 2012}

p "the first part of the script running by the iron_ruby interpreter" 
p "my_hash attributes:"
p "attr1: #{my_hash[:attr1]}"
p "attr2: #{my_hash[:attr2]}"
p "attr3: #{my_hash[:attr3]}"

# save the state of the script in an array where my_hash is the first element
p "hash_store_filename:#{hash_store_filename}"
File.open( hash_store_filename, 'w' ) do |out|
  YAML.dump( [my_hash], out )
end

这里是 ruby​​ 1.8 (demo_ruby.rb) 第二部分的代码

require "yaml"
p "running program:#{$0}"
hash_store_filename = ARGV[0]
p "hash_store_filename:#{hash_store_filename}"
ar = YAML.load_file(hash_store_filename)
my_hash=ar[0]

p "the second part of the script running by ruby 1.8.x interpreter"
p "my_hash attributes:"
p "attr1: #{my_hash[:attr1]}"
p "attr2: #{my_hash[:attr2]}"
p "attr3: #{my_hash[:attr3]}"

和发射器:

@ECHO OFF
REM file: demo.bat
SET TEMP_YAML=temp.yaml
ir demo_ir.rb %TEMP_YAML%
ruby demo_ruby.rb %TEMP_YAML%
del %TEMP_YAML%

如果您在并发环境中运行脚本,您可以在 Ironruby 脚本中生成 yaml 文件的唯一临时名称,从而避免两个进程(或线程)尝试写入同一个文件。

如果您愿意,可以使用一些 C# 代码行而不是 .bat 来集成脚本的两个部分,但这有点困难(恕我直言)

我使用以下方法成功测试了此解决方案:

C:\devkit\home\demo>ir -v
IronRuby 1.1.3.0 on .NET 4.0.30319.239

C:\devkit\home\demo>ruby -v
ruby 1.8.7 (2011-12-28 patchlevel 357) [i386-mingw32]

询问您是否需要澄清

于 2012-05-25T18:55:55.307 回答