Unpacking a value from a binary requires additional '.first'
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
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) # ...
Updated by mame (Yusuke Endoh) about 5 years ago
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
Yusuke Endoh email@example.com
Updated by naruse (Yui NARUSE) almost 5 years ago
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.