Noob question. I ran RubyMine's Code Inspect on a file containing this class.
class Square
attr_accessor :width
def area
@width * @width
end
end
I was surprised to get two warnings on the line @width * @width
:
Cannot find declaration for field '@width'
The attr section of the Style Guide wasn't helpful to me. Why is this a warning?
----Edit----
Ruby-Doc says this about attr-accessor
Defines a named attribute for this module, where the name is symbol.
id2name
, creating an instance variable (@name
) and a corresponding access method to read it. Also creates a method calledname=
to set the attribute. String arguments are converted to symbols.
To me, "Defines" means it has a "declaration". The warning message doesn't make sense. "Warning: Field may not be initialized before use" is more accurate.
I think this is a RubyMine issue (if it is an issue at all). RubyMine apparently uses its own code inspection protocol and doesn't use a standard Linter.
RubyMine's display of this warning in this situation is a known issue.
It seems @width
is not being initialized.
class Square
attr_accessor :width
def initialize(width)
@width = width
end
def area
@width * @width
end
end
x = Square.new(4)
#=> #<Square:0x00000002371ef8 @width=4>
x.area
#=> 16
Without that you would get an error when calling Square.new.area
(as the square has been defined without a width being set).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With