Issue #18573 has been updated by tenderlovemaking (Aaron Patterson).
matz (Yukihiro Matsumoto) wrote in #note-7:
Array.pack1 is unlikely because there is no connection
between the responsibilities of the method and the Array class. I also disagree with
String.pack1 for the same reason.
The most natural candidate is Object#pack1, but I question the need to pollute the
namespace for this trivial method.
Matz.
Feature #18897 introduced a specialized instruction for Array#hash, but it created a new
instruction called `opt_newarray_send`. I think we could leverage that instruction for
the case of an array literal + pack. That would avoid the array creation. I will try to
make a patch.
----------------------------------------
Feature #18573: Object#pack1
https://bugs.ruby-lang.org/issues/18573#change-104894
* Author: os (Shigeki OHARA)
* Status: Open
* Priority: Normal
----------------------------------------
# 概要
String#unpack1 の逆の Object#pack1 が欲しい。
# 背景
Array#pack というメソッドがありますが、レシーバーの Array の要素数が 1 つしかないことが良くあります。
``` ruby
[codepoint].pack('U')
[digest].pack('m0')
[mail_body].pack('M')
[ip_address].pack('N')
```
標準添付ライブラリーなどを眺めてみてもチラホラあるようです。
ですが、このようなケースで変換対象のオブジェクトをわざわざ Array でくるまなくてはいけないというのは面倒な気もします。
# 提案
String#unpack に対して String#unpack1 というメソッドがありますが、
Array#pack に対する Object#pack1 というメソッドを提案します。
イメージとしては以下のコードのような感じです。
``` ruby
class Object
def pack1(template, option = {})
[self].pack(template, **option)
end
end
```
# 議論・課題
* Object で良いかどうかは議論の余地があろうかと思います
* メソッド名が pack1 で良いかはわかりませんが、他とかぶる可能性は低いかと思います
--
https://bugs.ruby-lang.org/