Skip to content

Commit b50ddc0

Browse files
committed
Add String Interpolation With Instance Variables as a ruby til
1 parent 0ee07e9 commit b50ddc0

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
77
warrant a full blog post. These are mostly things I learn by pairing with
88
smart people at [Hashrocket](http://hashrocket.com/).
99

10-
_427 TILs and counting..._
10+
_428 TILs and counting..._
1111

1212
---
1313

@@ -333,6 +333,7 @@ _427 TILs and counting..._
333333
- [Set RVM Default Ruby](ruby/set-rvm-default-ruby.md)
334334
- [Show Public Methods With Pry](ruby/show-public-methods-with-pry.md)
335335
- [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md)
336+
- [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md)
336337
- [Summing Collections](ruby/summing-collections.md)
337338
- [Uncaught Exceptions In Pry](ruby/uncaught-exceptions-in-pry.md)
338339
- [`undef_method` And The Inheritance Hierarchy](ruby/undef-method-and-the-inheritance-hierarchy.md)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# String Interpolation With Instance Variables
2+
3+
When using regular variables with string interpolation in Ruby, they must be
4+
wrapped in curly braces (e.g. `"This is a #{variable}"`). With instance
5+
variables (and class and global variables) you can just use the _octothorp_
6+
followed directly by the variable.
7+
8+
Here is an example of this in action:
9+
10+
```ruby
11+
class Person
12+
def initialize(name)
13+
@name = name
14+
end
15+
16+
def whoami
17+
puts "I am #@name"
18+
end
19+
end
20+
21+
bob = Person.new("bob")
22+
#=> #<Person:0x007fdaf3291618 @name="bob">
23+
24+
bob.whoami
25+
# I am bob
26+
```
27+
28+
This is a handy shortcut, but may affect readability and/or result in an
29+
interpolation error at some point. Your mileage may vary.
30+
31+
h/t Josh Davey

0 commit comments

Comments
 (0)