I’d love to see better examples of using ``, but I’ve mostly seen it used to refactor this:

metadata = {}
metadata[:id] = user.id if user

That’s explicit. It creates a hash, adds a value if a condition is true, then returns the hash.

With ``, the code is more difficult to read, and requires the next person to know what `` does (“yields x to the block, and then returns x.”). 🤷‍♀️

{}.tap do |metadata|
metadata[:id] = user.id if user

@jkreeftmeijer I think a better example is when you don't originally have a variable:



foo(do_stuff.tap { |x| x.is_admin = true })

but in general I agree: nothing wrong with refactoring that one out into a variable.

@judofyr That’s a better example indeed. Instead of preventing an explicit return like in my example, this prevents having to store the result in a variable. But, exactly, I’d still prefer that.

result = do_stuff
result.is_admin = true

@jkreeftmeijer @judofyr I think there's some value in it for long methods where you want to explicitly limit the lifetime of a local var. It might even point out an Extract Method boundary.

Otherwise, I think I mainly use it for things like `array.tap(&:compact!)`, where a tempvar would just be noise.

@jgaskins @judofyr In cases more complex than my initial example, I’d prefer hiding these local variables in private convenience methods so they’re well-named and easy to look up.

I do think I like that symbol-proc syntax example works for methods that don’t return `self`, though. 🤔

Sign in to participate in the conversation

Follow friends and discover new ones. Publish anything you want: links, pictures, text, video. This server is run by the main developers of the Mastodon project. Everyone is welcome as long as you follow our code of conduct!