1

I am trying to convert unpacked value of 4 byte array? Is this possible in Ruby?

say I wrote b1 = b.unpack("N") and print value of b1 which is 1 . But when I try to convert b1 to some integer using .to_i console throws error test.rb:13: undefined methodto_i' for [118]:Array (NoMethodError)`

My code is following:

File.open('testfile','rb') do |file|
file.read.scan(/(.{4})(.{4})(.{4})(.*\w)(.{8})/).each do |a,b,c,d,e|
    if a == "cook"
    puts "test1"
    else
    puts "test2"
    end
    puts "output1"
    b1 = b.unpack("N")
    puts "output2"
    c1 = c.unpack("N")
    puts "output3"
    puts "output4"
    puts "output5"
end
end
4

1 回答 1

1

String#unpack always returns an array, even if there's only one value:

irb:01> s = "\x0\x0\x0*"
#=> "\u0000\u0000\u0000*"

irb:02> v = s.unpack('N')
#=> [42]

irb:03> v.class
#=> Array

You are confused because when you puts an array it outputs the to_s version of each value on its own line; in this case that looks like a single number:

irb:04> puts v
#=> 42

irb:05> puts [1,2,3]
#=> 1
#=> 2
#=> 3

In the future, when debugging your programs through print statements, use p instead of puts, as the output of it is similar to source code and designed to be clear:

irb:12> puts 42, "42", [42]
#=> 42
#=> 42
#=> 42

irb:13> p 42, "42", [42]
#=> 42
#=> "42"
#=> [42]

As @Dave commented, you need to extract the integer from the array to really use it as an integer:

irb:06> i = v.first  # or v[0]
#=> 42

irb:07> i.class
#=> Fixnum
于 2012-04-02T12:31:58.027 回答