Created
January 26, 2021 05:02
-
-
Save tomlin7/4909deda0698c266eb62a47e1d6b7d08 to your computer and use it in GitHub Desktop.
A greeting class for understanding basics of ruby.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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