Skip to content

Instantly share code, notes, and snippets.

@sephraim
Created September 12, 2025 14:24
Show Gist options
  • Save sephraim/481348950443f815d2f14a6d3ed3b5a5 to your computer and use it in GitHub Desktop.
Save sephraim/481348950443f815d2f14a6d3ed3b5a5 to your computer and use it in GitHub Desktop.
[Using getters / setters / class variables in Ruby]
class MyClass
attr_reader :my_var
def initialize
@my_var = "initial value"
end
def demonstrate
# IMPORTANT: `self` is OPTIONAL for getters but MANDATORY for setters
puts "1. Reading with 'my_var': #{my_var}" # Calls the getter
puts "2. Reading with 'self.my_var': #{self.my_var}" # Also calls the getter
# This creates a NEW local variable, it does NOT change @my_var
my_var = "local variable value"
puts "3. The local variable is now: #{my_var}"
puts "4. The instance variable is still: #{@my_var}" # Unchanged!
end
end
instance = MyClass.new
instance.demonstrate
# OUTPUT
# 1. Reading with 'my_var': initial value
# 2. Reading with 'self.my_var': initial value
# 3. The local variable is now: local variable value
# 4. The instance variable is still: initial value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment