Why Must I Explicitly Call Self on Accessor When Using the Array Union Operator |= in Ruby

Why must I explicitly call self on accessor when using the Array union operator |= in Ruby?

It's different.

values << value is method calling, which calls the method of :<< of Array.

While uniq_values |= value is just the short cut of uniq_values = uniq_values | value, here uniq_values will be parsed as the local variable.

Per the documentation:

"The local variable is created when the parser encounters the
assignment, not when the assignment occurs"

and

"When using method assignment you must always have a receiver. If you
do not have a receiver Ruby assumes you are assigning to a local
variable"

Ruby |= assignment operator

Bitwise OR assignment.

x |= y

is shorthand for:

x = x | y

(just like x += y is shorthand for x = x + y).

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

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.



Related Topics



Leave a reply



Submit