Classes and Hashes

I have many years of programming experience, but I am a newbie to Ruby. I have started by creating a Contact class that either contains hashes such as Addresses, Phone Numbers, Email Addresses, etc. Alternatively, I am trying to Addresses and the other classes as inheriting from the Contact class.

What I am seeking is feedback on both approaches. For the Hashes in the Contact class, I am looking for a simple code example of initializing and populating the hash.

For using inheritance, what is the syntax to access the “Home Address” of a contact. Person.Address[“Home”}?

Thanks for any help you can provide

Hi, welcome! One approach could be this:

class Person
	def initialize(name:, address:, phone:)
		@name, @address, @phone = name, address, phone

	def address
                # you can also use attr_reader(:address) instead of defining this method

person = 'Xman', address: {'Home' => 'The Earth'}, phone: '0003869723')

p person.address    # => {:Home=>"The Earth"}
p person.address['Home']         # "The Earth"

The other one could be this!

class Person

	def initialize(name:, home:, office: nil, phone: nil)
		@name = name
		@address = {'Home' => home, 'Office' => office}
		@phone = phone

person = 'Xman', home: 'Mars', office: 'Earth')

p person.address    # => {"Home"=>"Mars", "Office"=>"Earth"}
p person.address['Home']         # "Mars"

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs