Quantcast
Viewing all articles
Browse latest Browse all 10

Ruby Tip #1: No braces required to interpolate global, instance, or class variables

Right there on page 15 of the Pickaxe is where you’ll find today’s tip. When interpolating variables within a double quoted string, we typically use #{var_name} to interpolate variables. Ruby provides a shortcut for global, instance, and class variables (but not locals), making the brackets are optional.

#!/usr/bin/env ruby
dipsy_color = 'green'  # local
$lala_color = 'yellow' # global
@po_color   = 'red'    # instance
@@tinky_winky_color = 'purple' # class

puts "Dipsy is #{dipsy_color}"
puts "Lala is #$lala_color"
puts "Po is #@po_color"
puts "Tinky Winky is #@@tinky_winky_color"

This produces the following output:

Dipsy is green
Lala is yellow
Po is red
Tinky Winky is purple

For what it’s worth, I prefer the readability of the brackets. It’s just one of those little things you may have missed…


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 10

Trending Articles