Skip to content

Instantly share code, notes, and snippets.

@phlipper
Created April 9, 2015 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phlipper/1015c43d7f283ef8a2d4 to your computer and use it in GitHub Desktop.
Save phlipper/1015c43d7f283ef8a2d4 to your computer and use it in GitHub Desktop.
TECH603 Day 5 Warmup
# 1. Create a class named Country
class Country
end
# 2. Add the ability to read and write an attribute named "name". This should
# be done using two methods.
# HINT: the writer method has the `=` at the end
# HINT HINT: use an ivar to store the name in the scope of the class
class Country
def name
@name
end
def name=(name)
@name = name
end
end
# 3. Create an instance of your Country class
country = Country.new
# 4. Set the name attribute
country.name = "Angola"
# 5. Get and display the name attribute
puts country.name
# 6. Add support to read and write an attribute named "id", but this time use
# the Ruby macros for readers and writers.
class Country
# attr_reader :id
# attr_writer :id
attr_accessor :id
end
# 7. Set and get the id attribute
country = Country.new
country.id = "CID"
puts country.id
# 8. Modify country to allow you to pass the name and id in when the country
# is created.
class Country
# constructor
def initialize(name, id)
@name = name
@id = id
end
end
country = Country.new("Angola", "AGO")
puts country.name, country.id
# reopen the class and "monkey patch" the `name` method
class Country
def name
"NAME NAME NAME NAME NAME NAME NAME"
end
end
country = Country.new("Angola", "AGO")
puts country.name, country.id
# We can reopen any class!
class Fixnum
def +(other)
"Surprise!"
end
end
puts 1 + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment