2

The code below is taken from page 118 of the Pickaxe book. Can someone explain to me why we do not need to do #{@name} to do interpolation?

class TaxCalculator
  def get_tax(amount)
    "#@name on #{amount} = #{@block.call(amount)}"
  end
end
user2864740
  • 60,010
  • 15
  • 145
  • 220
JaTo
  • 2,742
  • 4
  • 29
  • 38

2 Answers2

4

When the expression to be interpolated is just a reference to a global, instance or class variable, then the braces can be omitted. The braces are only required for more complex expressions.

However, there is a debate about whether omitting the braces is a good idea from a style and readability perspective.

Vidya
  • 29,932
  • 7
  • 42
  • 70
2

There is already a good answer to this question here:

Why does string interpolation work in Ruby when there are no curly braces?

In short: It's possible to spare the {} when you use a global, a class or an instance variable.

Community
  • 1
  • 1
  • 1
    No need to duplicate an answer when there is already a sufficient answer both on this question and on the duplicate question. – sawa Nov 30 '13 at 01:15
  • This answer was written 4 minutes after Vidya's, which makes me think that it was written before Vidya's was posted - and misterbeaker simply missed that it had been posted in the meantime. – javawizard Dec 04 '14 at 08:39