Skip to content

Instantly share code, notes, and snippets.

@tomlin7
Created January 26, 2021 05:02
Show Gist options
  • Save tomlin7/4909deda0698c266eb62a47e1d6b7d08 to your computer and use it in GitHub Desktop.
Save tomlin7/4909deda0698c266eb62a47e1d6b7d08 to your computer and use it in GitHub Desktop.
A greeting class for understanding basics of ruby.
class MegaGreeter
attr_accessor :names
# Create the object
def initialize(names = 'world')
@names = names
end
# say hi to everybody
def say_hi
if @names.nil?
puts '...'
elsif @names.respond_to?('each')
# @names is a list of some kind, iterate!
@names.each do |name|
puts "Hello #{name}"
end
else
puts "Hello #{@names}"
end
end
def say_bye
if @names.nil?
puts '...'
elsif @names.respond_to?('join')
# join the list elements with commas
puts "Goodbye #{@names.join(', ')}. Come back soon:tm:!"
else
puts "Goodbye #{@names}. Come back soon:tm:"
end
end
end
if __FILE__ == $0
mg = MegaGreeter.new
mg.say_hi
mg.say_bye
# Change the name to Billy
mg.names = "Billy"
mg.say_hi
mg.say_bye
# change the name to an array of names
mg.names = %w[Albert Brenda Charles Dave Engelbert]
mg.say_hi
mg.say_bye
# Change to nil
mg.names = nil
mg.say_hi
mg.say_bye
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment