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:
I will now be doing something to this object
Now I am doing it
It is done
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Nice.
A common problem that I have been enjoying the use of
tap
on is populating an array with optional elements.Instead of:
... (which creates two Array objects) I have switched to ...
... or ...
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: