When I started my ruby journey, I wrote my study notes for people with other OO language experiences. Let's take a look at the magic ruby.
The first sample! First meeting.
# ! /Usr/bin/ENV 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 " "
Else
If @ 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
End
# Say bye to everybody
Def Say_bye
If @ Names. nil?
Puts " "
Else
If @ Names. respond_to? ( " Join " )
# @ Join the list elements with commas
Puts " Goodbye # {@ names. Join ( " , " )}. Come back soon! "
Else
Puts " Goodbye # {@ names }! "
End
End
End
End
If _ File __ = $0
MG = Megagreeter. New
MG. say_hi
MG. say_bye
# Change name to be "Zeke"
MG. Names = " Jaylee "
MG. say_hi
MG. say_bye
# Change the name an array of names
MG. Names = [ " Albert " , " Brenda " , " Coderlee " ]
MG. say_hi
MG. say_bye
# Change to nil
MG. Names = Nil
MG. say_hi
MG. say_bye
End