You can use Object#try from ActiveSupport to do this:
"hello".try(:tap) { |a| puts "yielded #{a.inspect}" }
nil.try(:tap) { |a| puts "yielded #{a.inspect}" }
try will attempt a method, but only if it's called on an object that's not nil.
On Thursday, 14 June 2012 at 11:01 AM, Steve H wrote:
> I'm looking for something built-in to Ruby that works kind of like
> Object#tap, but only yields if self is not nil.
>
> That is, can I do this without monkey-patching Object?
>
> If it's in Activesupport that's fine too. I feel like this method exists but
> I can't find it.
>
> class Object
> def tap_unless_nil
> if nil?
> nil
> else
> yield self
> end
> end
> end
>
> "hello".tap_unless_nil{ |a| puts "yielded #{a.inspect}" }
> nil.tap_unless_nil{ |a| puts "yielded #{a.inspect}" }
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby or Rails Oceania" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/rails-oceania/-/XkiiF0QABO0J.
> To post to this group, send email to [email protected]
> (mailto:[email protected]).
> To unsubscribe from this group, send email to
> [email protected]
> (mailto:[email protected]).
> For more options, visit this group at
> http://groups.google.com/group/rails-oceania?hl=en.
--
You received this message because you are subscribed to the Google Groups "Ruby
or Rails Oceania" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rails-oceania?hl=en.