如何使用Ruby解压数组转换为单一的价值? [英] How to convert unpacked array to single value using Ruby?

查看:120
本文介绍了如何使用Ruby解压数组转换为单一的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换成4字节数组解压价值?这是可能在Ruby中?

说我写了 B1 = b.unpack(N) B1 打印值,该值 1 。但是,当我尝试B1转换为使用.to_i控制台某个整数抛出误差 test.rb:13:未定义的方法 to_i[118]:阵列(NoMethodError)`

我的code为以下内容:

  File.open('testfile将,RB)做|文件|
file.read.scan(/({4})({4})({4})(* \\ w)的({8})/。。。)每个活动| A,B,C,D ,E |
    如果一个==厨师
    把测试1
    其他
    把TEST2
    结束
    把输出1
    B1 = b.unpack(N)
    把输出2
    C1 = c.unpack(N)
    把OUTPUT3
    把输出4
    把output5
结束
结束


解决方案

字符串#解压 总是返回一个数组,即使只有一个值:

  IRB:01> S =\\ X0 \\ X0 \\ X0 *
#=> \\ u0000的符\\ u0000 \\ u0000的*IRB:02> V = s.unpack('N')
#=> [42]IRB:03> v.class
#=>排列

您感到困惑,因为当你看跌它输出自身线上的每个值 to_s 版本的数组;在这种情况下的看起来的像一个单一的号码:

  IRB:04>把v
#=> 42IRB:05>看跌[1,2,3]
#=> 1
#=> 2
#=> 3

在未来,通过报表打印调试程序时,使用 P 而不是看跌,作为输出它类似于源$ C ​​$ c和设计是明确的:

  IRB:12>把42,42,[42]
#=> 42
#=> 42
#=> 42IRB:13取代;第42页,42,[42]
#=> 42
#=> 42
#=> [42]

作为@戴夫评论,你需要从数组中提取整数真正使用它作为一个整数:

  IRB:06> I = v.first#或v [0]
#=> 42IRB:07> i.class
#=> Fixnum对象

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

解决方案

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

这篇关于如何使用Ruby解压数组转换为单一的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆