Today I Learned

hashrocket A Hashrocket project

String Interpolation With Instance Variables

When using regular variables with string interpolation in Ruby, they must be wrapped in curly braces (e.g. "This is a #{variable}"). With instance variables (and class and global variables) you can just use the octothorp followed directly by the variable.

Here is an example of this in action:

class Person
  def initialize(name)
    @name = name

  def whoami
    puts "I am #@name"

bob ="bob")
#=> #<Person:0x007fdaf3291618 @name="bob">

# I am bob

This is a handy shortcut, but may affect readability and/or result in an interpolation error at some point. Your mileage may vary.

h/t Josh Davey

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.