Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top