Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to put operations inside #{these}? [closed]

Tags:

ruby

Like this:

puts "Today my ostrich laid #{@eggs_laid - @stillborn - @wolves_ate} valid eggs."

If this was literally the only place I'd be needing this specific calculation, is there any point in making a valid_eggs function?

like image 940
user2493615 Avatar asked Jun 19 '13 13:06

user2493615


People also ask

What is internal operation?

Internal Operations means use of the Programs by your employees or those of your subsidiaries or parent company and for the performance of consulting or research for third parties who engage you as an employee or independent contractor.

What is safe lifting operation?

safe lifting operation. It provides guidance for the practitioner in the planning and execution of a lifting operation. This CP is not intended to provide technical details on any specific lifting equipment; hence it is recommended to consult the manufacturer or supplier when more technical details are required.

What document must be established before a lifting operation could proceed?

Before you start any lifting operation, you must prepare the following: Lifting plan supported by a risk assessment (RA); Safe work procedure or method statement; Permit-to-work (PTW); and.


3 Answers

It's not inherently bad. But if the expression is complex, it reduces readability of the code. Here, I put the two snippets here, which one reads better?

puts "Today my ostrich laid #{@eggs_laid - @stillborn - @wolves_ate} valid eggs."

valid_eggs = @eggs_laid - @stillborn - @wolves_ate
puts "Today my ostrich laid #{valid_eggs} valid eggs."
like image 153
Sergio Tulentsev Avatar answered Nov 28 '22 11:11

Sergio Tulentsev


This is an opinion piece: yes and no.

If it's "complex"1 it likely belongs somewhere else.

If it's "simple"2 it's not an issue.

It all comes down to readability, maintainability, appropriate re-use, and not doing anything silly.


1. For varying values of "complex". 2. For varying values of "simple".

like image 26
Dave Newton Avatar answered Nov 28 '22 13:11

Dave Newton


Absolutely not. Putting code inside #{...} interpolators is a legitimate part of fun in Ruby. For readability, you might consider:

puts "Today my ostrich laid %s valid eggs." % ( @eggs_laid - @stillborn - @wolves_ate )

But note that % interpolation and #{...} interpolation are two different kinds of fun, which are not fully interchangeable.

like image 34
Boris Stitnicky Avatar answered Nov 28 '22 13:11

Boris Stitnicky