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
How to Know If an Io Is Empty Without Reading It
How to Display Error Messages in a Multi-Model Form with Transaction
Replacing an Element in Nested Array Ruby
Prawn Gem: How to Create the .Pdf from an *Existing* File (.Xls)
Rspec Hook After Report Gets Created
How to Multiply "5X3" String in Ruby
Heroku: Push Rejected, Failed to Compile Ruby App
Implicit User Creation with Authlogic and Authlogic Oauth Plugin
Shoulda/Rspec Matchers - Conditional Validation
Encrypt Data Bag from Inside of Ruby Without Relying on Knife
Print Unicode Escape Codes from Variable
How to Create Activerecord Style Validations Outside of Activerecord
Use Some Middleware Only for Specific Rack Website
Can You Append to Specific Elements in an Array Based on If Statement Conditions
Why Are Database Entries Being Automatically Created When I Visit the "New" Page