Instance Variables
Collapse Content
Show Content
Instance variables are available to the whole class and are created with @
:
class Dog
@name
end
@name
isn't currently accessible from outside the class. Ruby uses a method named initialize
to set up values when an object is created. (This is like Java's constructors.)
class Dog
def initialize(name)
@name = name
end
#getter
def name
@name
end
def bark
puts "Woof!"
end
end
Note the method name
above. This lets code outside the class get the value of @name
.1
We can now create a Dog:
doggy = Dog.new("Max") #creates new Dog named "Max"
puts doggy.name #calls Dog's `name` method, which returns @name
This prints out:
Max
1. Ruby also provides shortcuts for creating methods to access and change variables; see Ruby Classes.
Challenge
Copy your simple Product class form before and make it useful:
- Inside your Product class, create an
initialize
method that takes in 2 parameters and assigns their values to 2 instance variables named@name
and@description
. - Create 2 'getter' methods to return the value of @name and @description.
- Change your method
to_s
so it returns something more useful: the name of the product followed by the description. For example, a product named "Pencil" with a description "Writing implement" should return "Pencil Writing implement".
Need help? Click on the hints you need below.
If you named one parameter
Do the same thing for
name
in the method header, this will assign its value in the method body:
@name = name
.Do the same thing for
@description
.
See main content for creating a getter method for @name. Copy it and then do the same thing for @description.
Use string interpolation to to put variables inside one string. For example
" #{item} "
would create a string with a space before and after item
.
Challenge
Create a Product class as described above.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.