Is it okay to enter operations inside # {these}?

Like this:

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

If this was literally the only place where I needed this particular calculation, is there any point in making the function valid_eggs ?

+7
source share
5 answers

This is not inherently bad. But if the expression is complex, it reduces the readability of the code. Here I put here two fragments that are better read?

 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." 
+5
source

This is part of the opinion: yes and no.

If it is β€œcomplex” 1 it probably belongs somewhere else.

If it is β€œjust” 2 this is not a problem.

It all comes down to readability, maintainability, proper reuse, and doesn't do anything stupid.


1. For different values, "complex". 2. For different values ​​"simple".

+5
source

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

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

But note that interpolation % and interpolation #{...} are two different kinds of pleasure that are not completely interchangeable.

+3
source

I think this is understandable - at least your variable names make sense. The purist may say that you should extract it into the method, but in fact - YAGNI (you do not need it) also refers to ruby.

If you need to do this in second place, I would make it a method. You have already thought about it.

+2
source

Obviously, this is debatable, as are other response states.

One case where you must necessarily extract operations is when they have side effects.

While the expression is referentially transparent, it is only a matter of taste and subjective readability.

+1
source

All Articles