Can you give me an example?
A method is a function defined in the class. An attribute is an instance variable defined in the class.
A data attribute is exactly as it sounds; it's data, it is simply a property. A method is a procedure, an action, and this is exactly what a method attribute is.
A class is a kind of data type, just like a string, integer or list. When we create an object of that data type, we call it an instance of a class. The data values which we store inside an object are called attributes, and the functions which are associated with the object are called methods.
A method in Ruby is a set of expressions that returns a value. Within a method, you can organize your code into subroutines which can be easily invoked from other areas of their program. A method name must start a letter or a character with the eight-bit set.
Attributes are just a shortcut. If you use attr_accessor
to create an attribute, Ruby just declares an instance variable and creates getter and setter methods for you.
Since you asked for an example:
class Thing attr_accessor :my_property attr_reader :my_readable_property attr_writer :my_writable_property def do_stuff # does stuff end end
Here's how you'd use the class:
# Instantiate thing = Thing.new # Call the method do_stuff thing.do_stuff # You can read or write my_property thing.my_property = "Whatever" puts thing.my_property # We only have a readable accessor for my_readable_property puts thing.my_readable_property # And my_writable_propety has only the writable accessor thing.my_writable_property = "Whatever"
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