I really don’t get what a class is supposed to do, is it just like a container to group elements? And why do I need to define variables using @ or @@ at the beginning? Shouldn’t the scope be decided automatically depending on where I create a variable? Is there any JS equivalent to classes or is this a ruby specific concept?
of sorts, i more like to think about is a blueprint. It describes something, then we create an instance you build of this blueprint/class. Sort of like a house. you make a blueprint (class) and then build the house (instance of class)
A variable prefixed with @ is an instance variable, while one prefixed with @@ is a class variable. For example:
class House
def initialize
@@door = nil
@door = nil
@door
is specific for each instance (each house build from the blueprint), while @@door
is shared by all instances (all houses). If we build multiple houses and we change @@door
, the value changes for all instance of House
class.
no, look at this example:
def my_function()
$x = 3
y = 5
end
my_function()
puts $x
puts y
$x
is global while y
is local. We defined them at the same place (inside the function), yet there scope varies. So scope isn’t automatically determine by where a variable.
disclaimer: using global variable like i did above is bad practice, this is a purely demonstrative example.
@
and @@
don’t even relate to scope, its more behavioral. An instance variable is very different from a class variable.
OO is a concept in many language, JS has classes since es6, before there where only objects.
OO can also be found in php, python, c++ and many more.
Isn’t it easier to use a function or a proc for that? A class can call a numer of methods or procs and do something with it. I don’t really get why it should be used instead of a normal funciton.
class Dog
def initialize(name, breed)
@name = name
@breed = breed
end
end
seems to me to be just a more complicated version of
def dog(name, breed)
end
and the variables “name” or “breed” are automatically only accessible in a local scope when defining them as parameters of a function, so why do I need to re-define them with @?
yea, it is. But i was more focusing on explaining classes.
to access these properties (@name
and @breed
) in other methods of your class.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.