Project

General

Profile

Actions

Feature #21455

closed

Add a block argument to Array#join

Added by leoarnold (Leo Arnold) 21 days ago. Updated 9 days ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:122612]

Description

I sometimes come across code like this where
the Array#join at the end can easily
be overlooked or stands out like a sore thumb:

hex_string = string.bytes.map do |byte|
  format('%02X', byte)
end.join(' ')

It seems idiomatic and more succinct
to pass the block to Array#join directly:

hex_string = string.bytes.join(' ') do |byte|
  format('%02X', byte)
end

Pull Request: https://github.com/ruby/ruby/pull/13731


Related issues 1 (0 open1 closed)

Related to Ruby - Feature #21386: Introduce `Enumerable#join_map`RejectedActions
Actions #1

Updated by leoarnold (Leo Arnold) 21 days ago

  • Description updated (diff)
Actions #2

Updated by leoarnold (Leo Arnold) 21 days ago

  • Description updated (diff)
Actions #3

Updated by mame (Yusuke Endoh) 21 days ago

Updated by mame (Yusuke Endoh) 11 days ago

I have a different view on this proposal.

If Array#join were to accept a block, I would expect its behavior to relate directly to the "join" action itself, not the transformation of each element (which is the responsibility of map).

Specifically, it seems most appropriate for the block's return value to be used as the separator between elements. This would allow for dynamic separators based on context, such as the position of the join.

For example, this approach provides an elegant way to handle the Oxford comma:

items = ["Apple", "Banana", "Cherry"]

i = 0
str = items.join do
  i += 1
  if i == items.size - 2
    ", and "
  else
    ", "
  end
end

p str #=> "Apple, Banana, and Cherry"

I believe this approach is more intuitive and consistent.

To be clear, I am not making a counter-proposal here. My main point is that it feels illogical for Array#join to accept a block that performs a map-like operation, as that behavior is unrelated to the behavior of "join" itself.

Updated by matz (Yukihiro Matsumoto) 9 days ago

  • Status changed from Open to Rejected

It's fundamentally join_map we have rejected. Array#join should join, not mapping.
We are not going to add every enumerable method combined with map. filter_map is an exception.

Matz.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like1Like0