Hi, I have a very basic doubt on module attributes.
If a module has a class variable and instance variable how does it work?
module MyModule
@ivar = 10
@@cvar = 2
end
How and where do we use this kind of thing our code.
Also rails gives an accessor helper mattr_accessor and they use like
module MyModule
mattr_accessor :phone
end
Which is equivalent to
module MyModule
def phone=(a)
@@phone = a
end
def phone
@@phone
end
end
Can you pleAse explain shy and how we modules like this??
end
I thought of a module as a structure that holds reusable constants and
methods in a specific contexts.
Lucky D. wrote in post #1007172:
I thought of a module as a structure that holds reusable constants and
methods in a specific contexts.
Modules also can be used as namespaces.
module MyModule
@ivar = 10
@@cvar = ‘hello’
def self.get_ivar
@ivar
end
def self.get_cvar
@@cvar
end
end
puts MyModule.get_ivar
puts MyModule.get_cvar
–output:–
10
hello
I’m not sure whether there is a difference between the behavior of a
module instance variable and a module class variable. It is sort of an
unwritten rule that class variables should be ignored in ruby, and that
class instance variables should be used instead.
Also rails gives an accessor helper mattr_accessor and they use like
module MyModule
mattr_accessor :phone
end
Which is equivalent to
module MyModule
def phone=(a)
@@phone = a
end
def phone
@@phone
end
end
Can you pleAse explain shy and how we modules like this??
end
module Dog
@@age = 10
@@weight = 30
mattr_accesor :age, :weight
end