Array Function

Posted . Visible to the public.

Let’s say we’re making a wish list class. To add stuff to a wish list, we’ll first instantiate it. For maximum convenience of client programmers, we want to support all likely calling conventions for adding objects to the list. Naturally, we want them to be able to add a single object to the list. But if they pass an array of multiple items, we want to support this form as well. And if for some reason a nil is passed, we want to just quietly ignore it, instead of adding it to the list or raising an exception.

class WishList
  attr_reader :items

  def initialize
    @items = []
  end

  def add(*items)
    @items.concat(items.flat_map(&method(:Array)))
  end
end

list = WishList.new
list.add(["Fancy boots", "Boot socks"])
list.add(nil)
list.add("Rancilio Silvia Espresso Machine")
list.add("A Zeppelin", "200,000 cubic meters of helium")
list.items
# => ["Fancy boots",
#     "Boot socks",
#     "Rancilio Silvia Espresso Machine",
#     "A Zeppelin",
#     "200,000 cubic meters of helium"]

Note that Array({key: 'value'}) results in [[:key, 'value']] while ActiveSupport’s Array.wrap has less surprising behavior.

Array.wrap({key: 'value'})
# => [{:f=>1}]
Alexander M
Last edit
Alexander M
Posted by Alexander M to Ruby and RoR knowledge base (2016-10-25 12:32)