Project

General

Profile

Actions

Feature #12752

closed
Image

Unpacking a value from a binary requires additional '.first'

Feature #12752: Unpacking a value from a binary requires additional '.first'

Added by tagomoris (Satoshi Tagomori) over 9 years ago. Updated about 9 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:77249]

Description

When I parsed a binary protocol (msgpack) by String#unpack, there are many similar expressions, like below:

str = io.read(1)
length = str.unpack('C').first
case length
when 4
  data = io.read(4).unpack('N').first
# ...

I know that unpack returns "1 or more" values, but I think there are too many cases to return just one object.
Creating Array objects for return values requires additional cost to create Array object, and calling .first.

I'm happy if I can write the code above like this:

str = io.read(1)
length = str.unpack('C', 0) # index, or str.unpack('C', index: 0)
case length
when 4
  data = io.read(4).unpack('N', 0)
# ...

Image Updated by shyouhei (Shyouhei Urabe) over 9 years ago Actions #1 [ruby-core:77250]

  • Description updated (diff)

Image Updated by mame (Yusuke Endoh) over 9 years ago Actions #2 [ruby-core:77261]

There is more concise way:

length, = str.unpack('C')

You cannot use this in a method chain, though.

I actually understand your frustration, but I feel no difference between str.unpack('C', 0) and str.unpack('C')[0].

--
Yusuke Endoh

Image Updated by naruse (Yui NARUSE) about 9 years ago Actions #3 [ruby-core:78316]

How about Array#unpack1 ?

Image Updated by matz (Yukihiro Matsumoto) about 9 years ago Actions #4 [ruby-core:78317]

unpack1 looks so ad-hoc but surely is attractive.

Matz.

Image Updated by matz (Yukihiro Matsumoto) about 9 years ago Actions #5 [ruby-core:78452]

Go ahead.

Matz.

Image Updated by knu (Akinori MUSHA) about 9 years ago Actions #6 [ruby-core:78453]

With a qualifier or multiple directives given, would it raise an ArgumentError or just go ahead with the process and only return the first value?

Image Updated by naruse (Yui NARUSE) about 9 years ago Actions #7 [ruby-core:78456]

Akinori MUSHA wrote:

With a qualifier or multiple directives given, would it raise an ArgumentError or just go ahead with the process and only return the first value?

Just after processing the first value, it returns.

Image Updated by naruse (Yui NARUSE) about 9 years ago Actions #8

  • Status changed from Open to Closed

Applied in changeset r56959.


String#unpack1 [Feature #12752]

Returns the first value of String#unpack.

Actions

Also available in: PDF Atom