Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Class Relationships: How do I use methods and objects from another class?

Thanks for viewing my question! :)

I'm fairly new to programming in Ruby, and I'm having trouble understanding how to implement classes in my code, and having them inherit methods and variable from each other.

I have a class LightBulb, which looks like this:

class LightBulb
  def initialize( watts, on )
    @watts = watts
    @on = on
  end

  # accessor methods
  def watts
    @watts
  end

  def on
    @on
  end

  # other methods
  def turnon
    @on = true
  end

  def turnoff
    @on = false
  end

  def to_s
    "#{@watts}-#{@on}"
  end
end

and the driver program that works with the class:

# a lit, 30-watt bulb

b = LightBulb.new( 30, false )
b.turnon( )
Bulb    

# a 50-watt bulb

fiftyWatt = LightBulb.new( 50, false )
fiftyWatt.turnoff( )

...and I'm trying to create a class Lamp that has-a LightBulb and uses it at various times. I know that on the inheritance tree diagram, they are supposed to be next to each other (i.e. LightBulb--Lamp, instead of LightBulb<--Lamp), so I don't know if I should be using the < inheritance operator. Here's the basic structure I need for the Lamp class:

Lamp ( string make, string model, double cost, int watts )
-- accessors
string make( ) 
string model( ) 
-- methods
void turnon( ) # turn on the bulb
void turnoff( ) # turn off the bulb
--class members
string make
string model
double cost
LightBulb bulb

How would I be able to use the turnon() and turnoff() methods from the LightBulb class, as well as the bulb object, in the Lamp class?

Here's what I have for Lamp so far, but I'm sure most of it is incorrect:

class Lamp
    attr_accessor :watts
    def initialize(make, model, cost, watts)
        @make = make
        @model = model
        @cost = cost
        @watts = LightBulb.new(:watts)
    end

    def make
        @make
    end

    def model
        @model
    end

    def cost
        @cost
    end
end
like image 648
paulalucai Avatar asked Feb 20 '26 18:02

paulalucai


1 Answers

You definitely don't need inheritance here. You are composing these objects, a Lamp has a LightBulb. You're close, and all you really need to do is call the methods on LightBulb that you're missing:

class Lamp

  def initialize(make, model, cost, watts)
    @make = make
    @model = model
    @cost = cost
    @bulb = LightBulb.new(watts, false)
  end

  # ... 

  def turnon
    @bulb.turnon
  end

  def turnoff
    @bulb.turnoff
  end

end

So I changed @watts to @bulb, and dropped the :watts symbol, as you really need to pass the value of watts that was passed in. If you're interested, here is some more information on symbols.

like image 101
Nick Veys Avatar answered Feb 23 '26 10:02

Nick Veys