📝 Edit page
➕ Add page
Classes
Instance variable
Use single @
.
class Foo
def initialize(my_foo)
@my_foo = my_foo
end
def bar
puts @my_foo
end
end
f = Foo.new(12)
f.bar
# 12
Method calls
Call a method within a method using self
.
class Foo
def foo
puts 'Hello'
end
def bar
self.foo
end
end
f = Foo.new
f.bar
Static class variable
Use double @
.
class Foo
@@FOO = 'abc'
def bar
puts @@FOO
end
end
Attributes
Getter
You need a getter otherwise the variable is not available outside the instance.
class Foo
def initialize(protein)
@protein = protein
end
def protein
@protein
end
def protein=(value)
@protein = value
end
end
foo = Foo.new(21)
# Getter
foo.protein
# 21
# Setter
foo.protein = 100
Attribute accessor
See guide - How to Use attr_accessor, attr_writer & attr_reader and Ruby OOP.
Shorthand for the getter and setter.
class Foo
attr_accessor :protein
def initialize(protein)
@protein = protein
end
end
There are three kinds:
attr_accessor
- read and writeattr_reader
- read onlyattr_writer
- write only
Using a colon.
class Foo
attr_accessor :protein
def initialize(foo, bar, protein:)
@protein = protein
end
end
If you use attr_accessor :protein
you can do sets/gets on the field @protein
automatically.
api = Foo.new(debug: true)
puts api.debug
# true
api.debug = false
puts api.debug
# false
That is similar to Python:
def initialize(foo, bar, **, debug=None):