Skip to content

Instantly share code, notes, and snippets.

Last active December 14, 2015 20:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Only setting getter's apparently doesn't prevent manipulation of instance variables. The shovel is a great and dangerous too.
# create a class with an attr_reader for
# a string and an array
class Thing
attr_reader :arr
attr_reader :str
def initialize
@arr = []
@str = ""
# initialize the class
thing =
# putting the array and string work
# as we would expect
p thing.arr
# => []
p thing.str
# => ""
# but if we shovel into them, we can
# alter their state -- even though we
# only exposed a getter method
thing.arr << "hello"
p thing.arr
# => ["hello"]
thing.str << "hello"
p thing.str
# => "hello"
# Lets try protecting our vars using dup
class Protected
attr_accessor :exposed
def initialize
@exposed = "safe"
@safe = "safe"
def safe
# again, a sanity check to see that
# our values both equal "safe"
example =
p ==
# => true
# we'll shovel to try and modify them << " or not" << " or not"
# and test equality again
p ==
# => false
# we can see @safe keeps its original value
# => "safe"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment