user3358302
user3358302

Reputation: 2111

ruby DRY return value?

This may come across as a silly question, but my rails application is starting to get plagued by this code style:

def return_my_object
  @object = get_object
  some_function_work(@object)
  return @object
end

Are there general practices or ways to get rid or avoid the return @object code? So far I can't think of anything and it seems like cruft code.

Upvotes: 0

Views: 131

Answers (1)

Daniël Knippers
Daniël Knippers

Reputation: 3055

You could use Object#tap to simplify that code slightly. Tap yields the object to the block, and returns the object after the block finishes. Thus, it does not set @object to the value of some_function_work, but rather to the result of get_object. However, if some_function_work alters @object, this will obviously be reflected since it is the same instance.

That is:

def return_my_object
  @object = get_object.tap { |o| some_function_work(o) }
end

The last expression of the method (@object) will also be returned.

A minimal example is below, where {}.tap yields a new Hash instance to the block, which will be returned when the block finishes. Inside the block we alter the Hash, which is reflected in the result that is assigned to @object.

@object = {}.tap { |hash| hash[:key] = :value }
# { :key => :value }

Upvotes: 5

Related Questions