re: Idiomatic Ruby: writing beautiful code VIEW POST

FULL DISCUSSION
 

Nice.

A common problem that I have been enjoying the use of tap on is populating an array with optional elements.

Instead of:

[
  name,
  (address if address),
  (phone if phone)
].compact

... (which creates two Array objects) I have switched to ...

[].tap do |ary|
  ary << name
  ary << address if address
  ary << phone if phone
end

... or ...

[name].tap do |ary|
  ary << address if address
  ary << phone if phone
end

As is often the case, simple examples don't really do this justice. When you have a lot of complexity about what is going to be added and when, it comes into its own.

Semantically, what I particularly like is the way that tap lets you use a block to say:

  1. I will now be doing something to this object
  2. Now I am doing it
  3. It is done
code of conduct - report abuse