Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a variable defined inside class definition without decorator @ or @@?

In Ruby, such code is legal:

class Aclass
  m = 1
end

but semantically speaking, what will m be, and how is it supposed to be accessed?

like image 765
Jokester Avatar asked Jan 27 '26 01:01

Jokester


2 Answers

m is just a local variable. It can only be accessed from within the class definition. It could be used to bootstrap the class for instance, but it can't be accessed from anywhere else.

For example:

class Aclass

  m=1
  puts "m is #{m}"

end

That code would be run only once, when you require the file containing that class. This is somewhat analogous to Java's static initialisation blocks.

like image 109
leonardoborges Avatar answered Jan 28 '26 15:01

leonardoborges


I'm not sure what the semantic term for m is, but it's just a regular variable in the scope of the class. You won't be able to access it outside of the class though (not even in the methods defined in the class).

like image 25
cam Avatar answered Jan 28 '26 15:01

cam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!