尝试在 ruby 脚本中解码 bin 文件,但在运行脚本后出现以下错误 test.rb:57:in read': no implicit conversion of nil into String (TypeError) from script:57:in
'
知道可能是什么问题吗?
提前致谢
require 'bindata'
class Decode < BinData::Record # size 4+
uint32le :record_count
array :records, :type => :cube_main_bin_record, :initial_length => :record_count
end
begin
f = ARGV[0] unless ARGV[0].nil?
bin = File.read(f)
Decode.read(bin).records.each_with_index do |rec, num|
puts "Record #{num} #{rec.to_binary_s.length}"
p rec
end
end
因为File.read
需要一个字符串参数,并且f
当您在没有命令行参数的情况下调用脚本时默认为 nil
f = ARGV[0] unless ARGV[0].nil? # f defaults to nil when ARGV[0] is nil
bin = File.read(f) # bin = File.read(nil) BOOM
这是您的代码的重构:
...
f = ARGV[0]
abort "filename required" unless f
bin = File.read(f)
...
这些变化完成了两件事:
unless ARGV[0].nil?
不做任何有用的事情来简化代码会误导将来维护您的代码的任何人,包括您自己本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句