Reputation: 71
Trying to decode a bin file in ruby script but after running the script I get the following error test.rb:57:in read': no implicit conversion of nil into String (TypeError) from script:57:in
'
Any idea what could be the problem?
Thanks in advance
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
Upvotes: 0
Views: 10077
Reputation: 3366
Because File.read
requires a string parameter and f
defaults to nil when you invoke the script without a command line argument
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
Here is a refactoring of your code:
...
f = ARGV[0]
abort "filename required" unless f
bin = File.read(f)
...
These changes accomplish two things:
unless ARGV[0].nil?
which doesn't do anything useful will be misleading to anyone maintaining your code in the future, including yourselfUpvotes: 2