Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Polymorphism over conditionals
# Conditional reach-around
User = Struct.new(:name, :role) do; end
def greet(user)
if user.name && user.role
"Hello, I am an #{user.role} user. My name is #{user.name}."
elsif user.name
"Hello, my name is #{user.name}."
else
"Hello, I am a guest user. I have no name."
end
end
puts greet User.new
puts greet User.new('james')
puts greet User.new('james','admin')
# Polymorphism
class GuestUser
def greet
"Hello, I am a guest user. I have no name."
end
end
NormalUser = Struct.new(:name) do
def greet
"Hello, my name is #{name}."
end
end
AdminUser = Struct.new(:name) do
def role
'admin'
end
def greet
"Hello, I am an #{role} user. My name is #{name}."
end
end
def greet(user)
user.greet
end
puts greet GuestUser.new
puts greet NormalUser.new('james')
puts greet AdminUser.new('james')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.